簡體   English   中英

在增量搜索JS中設置突出顯示的文本樣式

[英]Styling highlighted text in incremental search JS

第一個StackOverflow問題 - 喔!

關於這個Javascript樣式的快速問題:

    //Search
$('#search').keydown(function(e) {
    setTimeout(function() {
        if ($('#search').val() == '') {
            $('#history h4').show();
            $('#history li li').show();
            return;
        }

        $('#history h4').hide();

        var search = $('#search').val().toLowerCase();

        $('#history li li').each(function() {
            var thisId = $(this).attr('id').substr(13);
            var item = $.grep(history, function(item) { return item.id == thisId; })[0];
            if (item.message.toLowerCase().indexOf(search) != -1 || item.link.toLowerCase().indexOf(search) != -1)
                $(this).show();
            else
                $(this).hide();
        });
    }, 1);
});
});

我在哪里將CSS樣式放在javascript中以突出顯示搜索結果中的字母?

<font class="highlight"></font>

這類似於在瀏覽器中使用Ctrl + F進行搜索。

任何幫助都會非常感激。 謝謝!

J.P

在你的第二個if語句中,你可以添加如下內容:

reg_expression = new RegExp("(" + search + ")","ig");
$(this).html($(this).html().replace(reg_expression, '<span class="highlight">' + "$1" + '</span>'));

請注意,我使用span而不是font作為highlight類。

另請注意,我假設您的li li僅包含文本而不包含html標簽,因為匹配search任何字符序列都將被<span>search</span>替換,因此如果您有例如鏈接,則可能會導致問題href值包含您的搜索詞。

順便說一句,你需要刪除所有spanfonts ,然后才能添加新的spanfonts

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM