Wooove,这太可惜了!
Javascript
var sel, range, nodevalue, startFound, stop;
function goThroughElements(el){
// If el is the start node, set startFound to true
if(el.isSameNode(range.startContainer)) startFound = true;
if(startFound){
// If this is the start node, replace the text like this: abcd[ef gh] --> abcdxx xx
if(el.isSameNode(range.startContainer)){
// \w stands for a word character
nodevalue = el.nodeValue.substring(range.startOffset).replace(/\w/g, 'x');
el.nodeValue = el.nodeValue.substring(0, range.startOffset) + nodevalue;
}
// If this is the end node, replace the value like this: [abc def]gh ij -> xxx xxxgh ij
else if(el.isSameNode(range.endContainer)){
nodevalue = el.nodeValue.substring(0,range.endOffset).replace(/\w/g, 'x');
el.nodeValue = nodevalue + el.nodeValue.substring(range.endOffset);
// Now we can stop
stop = true;
}
// If this is just a text node, replace the value by xxxx
else if(el.nodeType == 3){
el.nodeValue = el.nodeValue.replace(/\w/g, 'x')
}
}
// Loop trough el's brothers
while(el){
// Stop if we need to
if(stop) return;
// If this element has child nodes, call this function again with the first child node
if(el.hasChildNodes()){
goThroughElements(el.childNodes[0]);
}
// Jump to el's brother, or quit the loop
if(el.nextSibling)
el = el.nextSibling;
else
break;
}
}
$(document).ready(function() {
$(this).mouseup(function(){
// Get the selection
sel = window.getSelection();
range = sel.getRangeAt(0);
// Stop must be false if the last selected text node isn't found, startFound must be false when the start isn't found
stop = false; startFound = false;
if(range.collapsed == false){
// Check if the selection takes place inside one text node element
if(range.startContainer.isSameNode(range.endContainer)){
// ab[cdefg]h -> aaxxxxxh
nodevalue = range.startContainer.nodeValue;
range.startContainer.nodeValue = nodevalue.substring(0, range.startOffset) + nodevalue.substring(range.startOffset, range.endOffset).replace(/\w/g, 'x') + nodevalue.substring(range.endOffset);
} else {
// If the start node of the selection isn't the same as the end node, loop through all elements
goThroughElements(range.commonAncestorContainer.childNodes[0]);
}
// Collapse selection.
range.collapse(true);
}
});
});
示例
你当然可以try the code
也许这不是最佳解决方案,因为它从根开始搜索起始节点。从range.startContainer 和range.endContainer 的第一个公共父元素开始搜索会更快,但我不知道该怎么做...
编辑
我将 to-X 函数包装在 if(range.collapsed == false) 中并使用 range.commonAncestorContainer.childNodes[0] 来开始迭代从选择的开始和结束位置的公共父级的第一个子级开始的元素