开发者

Javascript/jQuery substring highlighting problem

开发者 https://www.devze.com 2023-03-30 05:29 出处:网络
I am using Javascript to calculate the offset and length of a substring selected on my page. This gets stored somewhere and later, when I hover over the text I want to highlight certain words in it us

I am using Javascript to calculate the offset and length of a substring selected on my page. This gets stored somewhere and later, when I hover over the text I want to highlight certain words in it using that offset and length in jQuery. Here is the basic code used for the highlight:

content = $("#reade开发者_运维知识库r").html();
newContent = content.substring(0,offset)+'<font style="color: red;">'+content.substring(offset,offset+length)+'</font>'+content.substring(offset+length,content.length);
content = $("#reader").html(newContent);

Now my problem is this: the offset and length are calculated over what is displayed on the screen. The actual HTML code, however, may also contain <p> or other tags. As a result, the text that I highlight gets "shifted", depending on the amount of HTML code present.

What is the easiest way to solve this?


This is not easily solvable. You shouldn’t calculate offset and length over the text, but over the HTML, if you want to work on the HTML afterwards. However, inserting HTML tags somewhere into an existing HTML string may lead to invalid nesting. And finally, you lose state like attached event handlers if you re-insert nodes as HTML code.


use

$("#reader").text()

instead of $("#reader").html() to get the text out of your content


I'd strip tags or use DOM methods - like. .nodeType, .nodeValue.

0

精彩评论

暂无评论...
验证码 换一张
取 消