如何用js替换页面选中的文字?
对选中的文字进行操作,比如改变样式,用标签将其包裹,删除该文字等操作。在平时经常遇到,今天就分享一方法,起个抛砖引玉的作用。
<
script
>
function surroundContent() {
var r;
if (document.selection) {
r = document.selection.createRange();
if (r.text != '') r.pasteHTML('<
a
href
=
"#"
>' + r.text + '</
a
>')
}
else if (window.getSelection) {
r = window.getSelection();
if (r.rangeCount > 0) {
r = r.getRangeAt(0);
var a = document.createElement('a');
a.href = '#';
r.surroundContents(a)
r.collapse(false);
}
}
}
</
script
>
转载请注明:三只源码 » 如何用js替换页面选中的文字