如何基于搜索突出显示整个div [英] How to highlight an entire div based on search

查看:111
本文介绍了如何基于搜索突出显示整个div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个示例jsfiddle 此处

I have a sample jsfiddle here.

你会看到我创建了几个div类。我可以搜索文本并获得突出显示的答案,但我希望能够搜索div的值并让整个div(在这种情况下为方框)突出显示或填充颜色。

You'll see I have several div classes created. I can search the text and get a highlighted answer, but I want to be able to search the value of the div and have that entire div (a square box in this case) highlight or fill up with color.

这是我用于隔离文本的javascript,但我无法解决上述问题......

Here's the javascript I have for isolating the text, but I can't get the above issue to work...

function doSearch(text) {
    if (window.find && window.getSelection) {
        document.designMode = "on";
        var sel = window.getSelection();
        sel.collapse(document.body, 0);

        while (window.find(text)) {
            document.getElementById("button").blur();
            document.execCommand("HiliteColor", false, "yellow");
            sel.collapseToEnd();
        }
        document.designMode = "off";
    } else if (document.body.createTextRange) {
        var textRange = document.body.createTextRange();
        while (textRange.findText(text)) {
            textRange.execCommand("BackColor", false, "yellow");
            textRange.collapse(false);
        }
    }
}

这可以做得更恰当吗用jQuery?

Can this be done more appropriately with jQuery?

推荐答案

在这里分叉你的小提琴。我添加了一行CSS(一个新类:突出显示)并将doSearch()函数缩小到这两行jQuery:

I forked your fiddle here. I added one line of CSS (a new class: highlight) and shrunk down the doSearch() function to these two lines of jQuery:

$('#content div').removeClass('highlight');
$('#content div:contains(' + text + ')').addClass('highlight');

它首先从内容div中的每个div中删除突出显示类,然后将类添加回任何那些包含所需文本的div。

It first removes the highlight class from every div inside the content div, then adds the class back to any of those divs that contain the desired text.

这篇关于如何基于搜索突出显示整个div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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