gpt4 book ai didi

javascript - 双击时更改所选文本的样式

转载 作者:行者123 更新时间:2023-11-29 10:15:35 25 4
gpt4 key购买 nike

我想更改双击事件发生时选择的样式文本,并想在该选定文本之后附加一些元素。问题是文本的选择可以在 DOM 的任何地方,所以我不能将双击事件绑定(bind)到某个特定的部分。

我试图搜索所选文本并找到它属于哪个部门,但我找不到,他们的任何 js 库是否可以找到该词并替换它?

最佳答案

试试这段代码

JS

$('body').dblclick(function(){
var range = window.getSelection().getRangeAt(0);
var selectionContents = range.extractContents();
var div = document.createElement("span");
div.style.backgroundColor = "yellow";
div.appendChild(selectionContents);
range.insertNode(div);

});

HTML

<div>
I want to change styling text that's selected when double click event happen and want to append some element after that selected text. Problem is that the selection of text can be anywhere from the DOM so I can not bind double click event to some particular division.
</div>

<div>
I want to change styling text that's selected when double click event happen and want to append some element after that selected text. Problem is that the selection of text can be anywhere from the DOM so I can not bind double click event to some particular division.
</div>


<div>
I want to change styling text that's selected when double click event happen and want to append some element after that selected text. Problem is that the selection of text can be anywhere from the DOM so I can not bind double click event to some particular division.
</div>

DEMO HERE

关于javascript - 双击时更改所选文本的样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22728203/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com