在考虑浏览器兼容性时,在span标记中选择文本的方法是什么?例如,我有:
jQuery().html('
Hello world lorem ipsum my good friend!');
我希望lorem ipsum部分被光标选中.
我有这个code选择文字:
function SelectText(element) {
var doc = document
, text = doc.getElementById(element)
, range, selection
;
if (doc.body.createTextRange) {
range = document.body.createTextRange();
range.moveToElementText(text);
range.select();
} else if (window.getSelection) {
selection = window.getSelection();
range = document.createRange();
range.selectNodeContents(text);
selection.removeAllRanges();
selection.addRange(range);
}
}
解决方法:
你的意思是这样的?
var i = 0;
function SelectText(element) {
var doc = document
, text = doc.querySelectorAll(element)
, range, selection
;
if (doc.body.createTextRange) {
range = document.body.createTextRange();
range.moveToElementText(text[i]);
range.select();
} else if (window.getSelection) {
selection = window.getSelection();
range = document.createRange();
range.selectNodeContents(text[i]);
selection.removeAllRanges();
selection.addRange(range);
}
i++;
if ( i === text.length ) i = 0;
}
document.onclick = function(e) {
if (e.target.className === 'click') {
SelectText('span');
}
};
Click me!
如果您只需要选择一个标记元素,则可以使用querySelector而不是querySelectorAll
这是.html()的一个例子
$(function() {
$('body').html('
Hello world lorem ipsum my good friend!');
})
function SelectText(element) {
var doc = document
, text = doc.querySelector(element)
, range, selection
;
if (doc.body.createTextRange) {
range = document.body.createTextRange();
range.moveToElementText(text);
range.select();
} else if (window.getSelection) {
selection = window.getSelection();
range = document.createRange();
range.selectNodeContents(text);
selection.removeAllRanges();
selection.addRange(range);
}
}
window.onload = function() {
SelectText('span');
};
标签:jquery,javascript
来源: https://codeday.me/bug/20190702/1355569.html