javascript 如何在按钮单击时选择 div 文本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31677451/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 14:10:23 来源:igfitidea点击:
How to select div text on button click?
提问by rajagopalx
I want to select the div content on click button.
我想在单击按钮上选择 div 内容。
HTML
HTML
<div id="divid">Hello This div content have to be select. </div>
<button onclick="selectText(divid);"> Select Div</button>
JS
JS
function selectText(divid) {
if (document.selection) {
var div = document.body.createTextRange();
div.moveToElementText(document.getElementById("divid"));
div.select();
}
else {
var div = document.createRange();
div.setStartBefore(document.getElementById("divid"));
div.setEndAfter(document.getElementById("divid"));
window.getSelection().addRange(div);
}
}
回答by Pierre Irani
Try the below @Rajagopal Subramanian
试试下面的@Rajagopal Subramanian
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().addRange(range);
}
}
<div id="divid">Hello This div content have to be select.</div>
<button onclick="selectText('divid')">Select</button>
回答by Max
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().addRange(range);
}
}
回答by Surendra Singh Rana
I hope it will help you.
我希望它会帮助你。
html code
html代码
<div id="divid">Hello This div content have to be select. </div>
<button id="hit"> Select Div</button>
demo.js
演示.js
$(document).ready(function(){
$('#hit').on('click', function(){
var sav = $('#divid').html();
alert(sav);
});
});