【发布时间】:2017-02-08 12:53:17
【问题描述】:
我遇到了一个问题,我有这样的描述性原始文本 -
<p>I am using the following code to change the color of text but it is not working.. Can anyone help me with this? the soloution in javascript or jquery anything is fine..</p>
现在我的要求是
- 在鼠标向上事件中查找特定选定文本的位置(范围)
- 在整个操作过程中为选定的文本着色
我写的代码
$(document).ready(function() {
if (!window.Wafer) {
Wafer = {};
}
Wafer.Selector = {};
/* Function to get selected string as a object
* works for all browser and also handle for old browser like
* ie9,firfox 18 as discussed
*/
Wafer.Selector.getSelected = function() {
$selObj = '';
if (window.getSelection) {
$selObj = window.getSelection();
} else if (document.getSelection) {
$selObj = document.getSelection();
} else if (document.selection) {
$selObj = document.selection.createRange().text;
}
//console.log($selObj);
return $selObj;
}
//holding the selector string in variable on mouseup event
Wafer.Selector.mouseup = function() {
$selector = Wafer.Selector.getSelected();
$start = $selector.anchorOffset;
$end = $selector.focusOffset;
console.log($start, $end);
//I call this to wrap selected text under span
selectText('#f90');
}
//This will tell jquery to fire when "mouseup" event will occur
$(document).on("mouseup", Wafer.Selector.mouseup);
});
function selectText(hexColor) {
var selection = window.getSelection().getRangeAt(0);
var selectedText = selection.extractContents();
var span = document.createElement('span');
span.style.backgroundColor = hexColor;
span.className = 'selected-text';
span.appendChild(selectedText);
selection.insertNode(span);
}
在函数 selectText 中我曾经得到 window.getSelection().getRangeAt(0); 可能与 window.getSelection() 冲突> 并且两者都返回具有 anchoroffset 和 focusoffset 键的对象,因此无法获得正确的文本范围
有什么方法可以清除选中的文本范围吗?
关注了几个堆栈帖子,例如this,但这些帖子部分满足了我的要求并且代码有问题。 提前致谢。
【问题讨论】:
标签: javascript jquery