如何使用javascript选择整个HTML文档。
我尝试过这些功能,但是工作!!
function SelectAll()
{
document.body.focus();
document.body.select();
}
function SelectAll()
{
document.body.select();
}
我的整个代码是
<head>
<script type="text/javascript">
function SelectAll()
{
document.body.focus();
document.body.select();
}
</script>
</head>
<body>
<div>LaLa, Lala, laLa , lala, lalala, tralala, some other text</div>
<br />
<input type="text" id="findField" value="lala" size="20" />
<button onclick="SelectAll();">Find!</button>
</body>
答案 0 :(得分:2)
通过Satya-Weblog:
(function() {
function selectText(element) {
var doc = document
, text = element
, range, selection
;
if (doc.body.createTextRange) { //ms
range = doc.body.createTextRange();
range.moveToElementText(text);
range.select();
} else if (window.getSelection) { //all others
selection = window.getSelection();
range = doc.createRange();
range.selectNodeContents(text);
selection.removeAllRanges();
selection.addRange(range);
}
}
preTags = document.getElementsByTagName('document.body');
for(var i=0;i<preTags.length;i++) {
preTags[i].onclick = function() {selectText(this)};
}
})();
答案 1 :(得分:0)
你可以像这样写
(function() {
function selectText(element) {
var doc = document
, text = element
, range, selection
;
if (doc.body.createTextRange) { //ms
range = doc.body.createTextRange();
range.moveToElementText(text);
range.select();
} else if (window.getSelection) { //all others
selection = window.getSelection();
range = doc.createRange();
range.selectNodeContents(text);
selection.removeAllRanges();
selection.addRange(range);
}
}
preTags = document.getElementsByTagName('document.body');
for(var i=0;i<preTags.length;i++) {
preTags[i].onclick = function() {selectText(this)};
}
})();
答案 2 :(得分:0)
答案 3 :(得分:0)
要选择元素内的所有文本,请使用此简单代码。它将使用黄色突出显示整个元素/标记区域,并在单击时选择其中的文本。
document.onclick = function(event) {
var range, selection;
event.target.style.backgroundColor = 'yellow';
selection = window.getSelection();
range = document.createRange();
range.selectNodeContents(event.target);
selection.removeAllRanges();
selection.addRange(range);
};
要选择整个文档中的所有文本,您可以修改此代码,如下所示:
document.onclick = function(event) {
var range, selection;
var doc = document.body;
doc.style.backgroundColor = 'yellow';
selection = window.getSelection();
range = document.createRange();
range.selectNodeContents(doc);
selection.removeAllRanges();
selection.addRange(range);
};
答案 4 :(得分:0)
选择页面上的所有文本
document.body.innerText
答案 5 :(得分:-1)
document.execCommand(“ selectAll”);
https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand#Commands