【问题标题】:Contents of a div tag selected on button push - javascript [duplicate]按下按钮时选择的 div 标签的内容 - javascript [重复]
【发布时间】:2018-10-05 19:05:01
【问题描述】:

经过一些帮助,我对 Javascript 还比较陌生,当用户单击按钮时,我得到了想要选择的 div 标记的内容,但我无法让它工作。相对论似乎很简单,但我已经玩了几个小时,找不到解决方案

<div id="targetText">content content </div>

<button type="button" onclick="selectBox()">Push to Select</button>

使用以下Javascript

function selectBox() {
document.getElementById("targetText").select();
}

但是当我点击按钮时没有任何反应!

当我要求它选择输入时它工作正常(如下所示),但我要选择的内容在 div 中

<input type="text" id="targetText" value="content content">

有什么建议吗?提前致谢

【问题讨论】:

  • 我推荐重复的第二个答案-window.getSelection().selectAllChildren( document.getElementById('targetText'));

标签: javascript html select


【解决方案1】:
<button type="button" onclick="selectBox(document.getElementById('targetText'))">Push to Select</button>

function selectBox(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);

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-02
    • 2019-10-29
    • 1970-01-01
    • 1970-01-01
    • 2011-11-10
    • 1970-01-01
    • 1970-01-01
    • 2018-08-10
    相关资源
    最近更新 更多