单击鼠标即可选择所有DIV文本

Acy*_*yra 128 javascript css

当用户点击DIV时,如何突出显示/选择DIV标签的内容......我们的想法是突出显示/选择所有文本,这样用户就不需要用鼠标手动突出显示文本了错过了一些文字?

例如,假设我们有一个DIV如下:

<div id="selectable">http://example.com/page.htm</div>
Run Code Online (Sandbox Code Playgroud)

...当用户点击任何该URL时,整个URL文本都会突出显示,以便他们可以轻松地在浏览器中拖动所选文本,或者通过右键单击复制完整的URL.

谢谢!

Den*_*ski 180

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);
    }
}
Run Code Online (Sandbox Code Playgroud)
<div id="selectable" onclick="selectText('selectable')">http://example.com/page.htm</div>
Run Code Online (Sandbox Code Playgroud)

现在你必须将ID作为参数传递,在这种情况下是"可选择的",但它更全局,允许你在任何地方多次使用它,而不像chiborg提到的那样使用jQuery.

  • 顺便说一句,您可以轻松地将其转换为jQuery click事件处理程序,将`document.getElementById('selectable')`替换为`this`.然后你可以不显眼地将功能添加到几个元素中,例如容器中的几个div:`jQuery('#selectcontainer div').click(selectText);` (8认同)
  • 在Chrome版本36+中,这将返回错误"不支持不连续选择".解决方案是在`window.getSelection().addRange(range);之前添加`window.getSelection().removeAllRanges();`. (5认同)
  • 这适用于Chrome,FF,Safari(Mac)以及Chrome和IE(Windows 9 +,8未经测试).但它似乎不适用于iPad Mini(iOS6)或iPhone 4上的Safari,不确定其他iOS或Android. (3认同)

isa*_*pir 110

2017年更新:

要选择节点的内容,请调用:

window.getSelection().selectAllChildren(
    document.getElementById(id)
);
Run Code Online (Sandbox Code Playgroud)

这适用于所有现代浏览器,包括IE9 +(在标准模式下).

以下原始答案已经过时,因为window.getSelection().addRange(range); 已被弃用


原答案:

以上所有示例均使用:

function select(id) {
  window.getSelection()
    .selectAllChildren(
      document.getElementById("target-div") 
    );
}
Run Code Online (Sandbox Code Playgroud)

但问题在于它选择了Node本身,包括DIV标签等.

要根据OP问题选择节点的文本,您需要调用:

#outer-div  { padding: 1rem; background-color: #fff0f0; }
#target-div { padding: 1rem; background-color: #f0fff0; }
button      { margin: 1rem; }
Run Code Online (Sandbox Code Playgroud)

所以完整的代码片段是:

<div id="outer-div">
  <div id="target-div">
    Some content for the 
    <br>Target DIV
  </div>
</div>

<button onclick="select(id);">Click to SELECT Contents of #target-div</button>
Run Code Online (Sandbox Code Playgroud)

  • 您的解释保存谷歌另一个查询.来自我的+1 (5认同)

小智 40

有纯CSS4解决方案:

.selectable{
    -webkit-touch-callout: all; /* iOS Safari */
    -webkit-user-select: all; /* Safari */
    -khtml-user-select: all; /* Konqueror HTML */
    -moz-user-select: all; /* Firefox */
    -ms-user-select: all; /* Internet Explorer/Edge */
    user-select: all; /* Chrome and Opera */

}
Run Code Online (Sandbox Code Playgroud)

user-select是CSS模块4级规范,目前是草案和非标准CSS属性,但浏览器支持它很好 - 请参阅caniuse.com/#feat=user-select.

在MDN上阅读更多用户选择,在w3scools中播放

  • +1很棒的优雅解决方案!测试于2017年9月,可在FireFox和Chrome上完美运行**但不能在MICROSOFT EDGE中使用!?**有任何想法为什么不解决以及如何解决?谢谢! (3认同)

小智 13

Neuroxik的答案非常有用.我在使用Chrome时遇到了麻烦,因为当我点击外部div时,它无效.我可以在添加新范围之前解决它删除旧范围:

function selectText(containerid) {
    if (document.selection) {
        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);
    }
}
<div id="selectable" onclick="selectText('selectable')">http://example.com/page.htm</div>
Run Code Online (Sandbox Code Playgroud)


bob*_*bob 9

对于内容可编辑的东西(不是常规输入,您需要使用selectNodeContents(而不仅仅是selectNode).

注意:所有对"document.selection"和"createTextRange()"的引用都是针对IE 8及更低版本...如果你试图做这样棘手的事情,你可能不需要支持那个怪物.

function selectElemText(elem) {

    //Create a range (a range is a like the selection but invisible)
    var range = document.createRange();

    // Select the entire contents of the element
    range.selectNodeContents(elem);

    // Don't select, just positioning caret:
    // In front 
    // range.collapse();
    // Behind:
    // range.collapse(false);

    // Get the selection object
    var selection = window.getSelection();

    // Remove any current selections
    selection.removeAllRanges();

    // Make the range you have just created the visible selection
    selection.addRange(range);

}
Run Code Online (Sandbox Code Playgroud)


Tyl*_*ter 6

使用文本区域字段,您可以使用:(通过Google)

<form name="select_all">

    <textarea name="text_area" rows="10" cols="80" 
    onClick="javascript:this.form.text_area.focus();this.form.text_area.select();">

    Text Goes Here 

    </textarea>
</form>
Run Code Online (Sandbox Code Playgroud)

这就是我看到大多数网站都这样做的方式.他们只是用CSS设计它,所以看起来不像textarea.


Sim*_*rfe 5

此代码段提供了您需要的功能.您需要做的是向该div添加一个事件,该事件激活其中的fnSelect.一个你完全不应该做而且可能不会工作的快速黑客,看起来像这样:

document.getElementById("selectable").onclick(function(){
    fnSelect("selectable");
});
Run Code Online (Sandbox Code Playgroud)

显然假设已包含链接到代码段.


小智 5

我发现将此函数包装为jQuery插件很有用:

$.fn.selectText = function () {
    return $(this).each(function (index, el) {
        if (document.selection) {
            var range = document.body.createTextRange();
            range.moveToElementText(el);
            range.select();
        } else if (window.getSelection) {
            var range = document.createRange();
            range.selectNode(el);
            window.getSelection().addRange(range);
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

因此,它成为可重用的解决方案.然后你可以这样做:

<div onclick="$(this).selectText()">http://example.com/page.htm</div>
Run Code Online (Sandbox Code Playgroud)

它将在div中选择测试.


小智 5

试试这个,将 altn 添加到 oncontextmenu 将 gice 快速访问允许以这种方式输入的扩展。

<div onclick='window.getSelection().selectAllChildren(this)' id="selectable">http://example.com/page.htm</div>
Run Code Online (Sandbox Code Playgroud)