"일꾼이 일을 잘하려면 먼저 도구를 갈고 닦아야 한다." - 공자, 『논어』.
첫 장 > 프로그램 작성 > How Can I Programmatically Select All Text Within a DIV on Mouse Click?

How Can I Programmatically Select All Text Within a DIV on Mouse Click?

2025-03-26에 게시되었습니다
검색:862

How Can I Programmatically Select All Text Within a DIV on Mouse Click?

Programmatically Selecting DIV Text on Mouse Click

Question

Given a DIV element with text content, how can the user programmatically select the entire text within the DIV with a single mouse click? This allows users to easily drag and drop the selected text or copy it directly.

Solution

To select the text within a DIV element on a single mouse click, you can utilize the following JavaScript function:

function selectText(containerid) {
    if (document.selection) { // IE
        var range = document.body.createTextRange();
        range.moveToElementText(document.getElementById(containerid));
        range.select();
    } else if (window.getSelection) {
        var range = document.createRange();
        range.selectNode(document.getElementById(containerid));
        window.getSelection().removeAllRanges();
        window.getSelection().addRange(range);
    }
}

Implementation

To implement this functionality:

  1. Include the function above in your JavaScript code.
  2. Add a click event handler to your DIV element, invoking the selectText() function with the DIV's ID as an argument.
<div>

With this code, when users click anywhere within the DIV element, the entire text within that DIV will be highlighted and selected, allowing for easy manipulation or copying.

최신 튜토리얼 더>

부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.

Copyright© 2022 湘ICP备2022001581号-3