突出显示元素中的子字符串 [英] Highlight substring in element

查看:54
本文介绍了突出显示元素中的子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在事件中突出显示div元素中特定子字符串的最佳方法是什么? 突出显示,我的意思是应用一些CSS样式,例如黄色背景或其他东西.

What is the best way to highlight a specific substring in a div element in an event? By highlight, I mean apply some CSS style, like yellow background or something.

基本上,我需要一个简单的JS客户端函数,其形式为:

Basically I need a simple JS client side function of the form:

function (element, start, end) { 
  // element is the element to manipulate.  a div or span will do
  // start and end are the start and end positions within the text of that
  // element where highlighting should be.
  // do the stuff
}

只有一个突出显示处于活动状态.

Only one highlight will be active.

推荐答案

您将需要在其自己的<span>标记中包装所需的文本,以便为该文本赋予自己的样式.使用您请求的函数定义,您可以像这样进行操作:

You will need to wrap the text that you want to in it's own <span> tag so you can give that text its own style. Using your requested function definition, you could do it like this:

function (element, start, end) { 
    var str = element.innerHTML;
    str = str.substr(0, start) +
        '<span class="hilite">' + 
        str.substr(start, end - start + 1) +
        '</span>' +
        str.substr(end + 1);
    element.innerHTML = str;
}

然后,您可以为hilite类定义CSS,以控制该文本的样式.

You can then define CSS for the class hilite to control the style of that text.

.hilite {color: yellow;}

这假定开始和结束是您要突出显示的第一个和最后一个字符的innerHTML的索引.

This assumes that start and end are indexes into the innerHTML of the first and last characters that you want highlighted.

如果您希望能够在同一个元素上反复调用它(以移动高光),可以这样做:

If you want to be able to call it repeatedly on the same element (to move the higlight around), you could do it like this:

function (element, start, end) {
    var item = $(element);
    var str = item.data("origHTML");
    if (!str) {
        str = item.html();
        item.data("origHTML", str);
    }
    str = str.substr(0, start) +
        '<span class="hilite">' + 
        str.substr(start, end - start + 1) +
        '</span>' +
        str.substr(end + 1);
    item.html(str);
}

这篇关于突出显示元素中的子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆