使用位置值以编程方式选择div中的文本属于该文本
我有一个div,里面有一个文本。我希望根据字符的位置值以编程方式选择该文本的一部分。
Hello world. I am a friend.
我希望选择“llo world”部分( 我的意思是突出/选择就像在输入/ textarea中选择内容一样 )。 在那种情况下,位置值是第一(3)和最后(10)。
如何使用位置值以编程方式执行此操作?
这是一个简单的方法:
function selectTextRange(obj, start, stop) { var endNode, startNode = endNode = obj.firstChild startNode.nodeValue = startNode.nodeValue.trim(); var range = document.createRange(); range.setStart(startNode, start); range.setEnd(endNode, stop + 1); var sel = window.getSelection(); sel.removeAllRanges(); sel.addRange(range); } selectTextRange(document.getElementById('textdiv'), 3, 10);
Hello world. I am a friend.
代码没有任何错误检查。 使用风险自负!
function highlight(pattern) { var text = $("#textdiv").text(); var around = text.split(pattern); $("#textdiv").html(around[0] + "" + pattern + "" + around[1]); } $(document).ready(function() { highlight("world"); })
.highlight { background-color: yellow; }
Hello world. I'm Hugo!
尝试使用.html()
, String.prototype.slice()
。 要选择“llo world”,请使用参数.slice()
调用.slice()
$("#textdiv").html(function(i, html) { var selected = html.slice(3, 12); return html.replace(new RegExp("("+selected+")"), "$1") })
Hello world. I am a friend.