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

时间:2014-03-29 07:15:17

标签: javascript jquery dom

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

我试图搜索选定的文字并找到它们的哪个部门,但我无法找到,是他们的任何js库找到该单词并替换它?

1 个答案:

答案 0 :(得分:4)

试用此代码

<强> 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