我有以下javascript,当我选择文本并单击按钮时,它会突出显示文本。
$('.highlight').on("click", function (e) {
selected = getSelection();
range = selected.getRangeAt(0);
newNode = document.createElement("span");
newNode.setAttribute("class", "highlighted");
range.surroundContents(newNode);
});
function getSelection() {
var seltxt = '';
if (window.getSelection) {
seltxt = window.getSelection();
} else if (document.getSelection) {
seltxt = document.getSelection();
} else if (document.selection) {
seltxt = document.selection.createRange().text;
} else return;
return seltxt;
} 然而,这在我的p标记中创建了许多杂乱的span类。是否可以立即对选定的文本进行着色,而不必将其包装在跨距中?
这样做的另一个原因是,我想检查选定的文本是否已经具有黄色背景,如果是,则将其设置为透明(可能在两种颜色之间切换)
发布于 2015-04-02 22:06:36
像这样怎么样?请记住,这会向您的页面添加一个样式片段,您可能希望根据需要将其删除。现在,它也会在选定内容上突出显示文本,否则。
$(".highlight").on("click", function() {
!$("#selection").length && $("<style id=\"selection\">::-moz-selection { background: #111; color: #fff; } ::selection { background: #111; color: #fff; }</style>").appendTo("head");
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>This is some text. Select me to see my color and background color change!</p>
<button class="highlight">Click Me</button>
需要注意的是,::selection已经被removed from the spec。它可能不会对所有用户都可靠地工作。

https://stackoverflow.com/questions/29414380
复制相似问题