【问题标题】:jquery highlight on search of multiple words separated with spacejquery在搜索用空格分隔的多个单词时突出显示
【发布时间】:2013-06-04 05:43:12
【问题描述】:

我已经设置了一个插件来突出输入输入的单词。 你可以在 jsfiddle 中看到它:http://jsfiddle.net/K5PmD/

它可以工作,但我正在尝试修改插件,如果您输入例如“Donec”并突出显示,您可以在“Donec”之后在同一输入中按空格并输入例如“Mauris”和然后这个词也会和第一个词一起突出显示,即使它们不在文本中彼此(“.... Donec Mauris ...”),而是在文本中的某个地方。

html:

<body>
<input type="text" class="span1 disabled" id="field1" name="field1"><br> 

<p>
 Vestibulum rhoncus urna sed urna euismod, ut cursus eros molestie.
Nulla sed ante ut     diam gravida auctor eu quis augue. 
Donec eget diam malesuada, consectetur orci at, ultrices tellus. 
Duis id dui vel sem consequat rutrum eget non orci.
 Nullam sit amet libero odio. Vestibulum sapien sapien, 
molestie quis porta nec, sodales nec felis. 
 Mauris vehicula, erat eu consectetur viverra, 
dui tellus laoreet dolor, quis faucibus turpis eros non mi.  
</p>  
</body>

脚本:

$(function() {
$('#field1').bind('keyup change', function(ev) {
    // pull in the new value
    var searchTerm = $(this).val();

    // remove any old highlighted terms
    $('body').removeHighlight();

    // disable highlighting if empty
    if ( searchTerm ) {
        // highlight the new term
        $('body').highlight( searchTerm );
    }
    });
});

css

.highlight {
background-color: #fff34d;
-moz-border-radius: 5px; /* FF1+ */
-webkit-border-radius: 5px; /* Saf3-4 */
border-radius: 5px; /* Opera 10.5, IE 9, Saf5, Chrome */
-moz-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.7); /* FF3.5+ */
-webkit-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.7); /* Saf3.0+, Chrome */
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.7); /* Opera 10.5+, IE 9.0 */
}

.highlight {
padding:1px 4px;
margin:0 -4px;
}

这个插件有可能的解决方案吗?或者你可以推荐一些其他更好的插件来满足我的愿望?

如果你有什么可以更新我的 jsfiddle 并把它发回来......

【问题讨论】:

    标签: jquery input highlight words


    【解决方案1】:

    您正在使用的插件非常简单,严格来说不会匹配字符串数组,也不会分离单词本身。但通常这是自然的匹配方式。但是您可以通过分离单词并自己调用 highlight 来在代码中处理它。

    $(function() {
        $('#field1').bind('keyup change', function(ev) {
            // pull in the new value
            var searchTerm = $(this).val();
    
            // remove any old highlighted terms
            $('body').removeHighlight();
    
            // disable highlighting if empty
            if ( searchTerm ) {
                var terms = searchTerm.split(/\W+/);
               $.each(terms, function(_, term){
                  $('body').highlight(term.trim());
                });                          
    
            }
        });
    });
    

    Demo

    这是另一个plugin,您可以使用它来突出显示字符串数组。

    【讨论】:

    • 谢谢!我对jquery编码不太熟悉......我尝试了一些你之前链接过我的插件,但没有让它工作......有没有在线演示?我找不到它...
    • @dzordz 我会在周末添加它并通知你..我自己没有尝试过。但会尽力帮助你。我刚刚找到它的文档
    • @dzordz :) 是的,我会标记你的名字并在你的问题中通知你,这样你就会知道.. :)
    • 我对这个插件还有一件事要做,但我会提出新问题,所以这里不会变得混乱
    • 不知何故崩溃(因为重叠)与“au ug”
    猜你喜欢
    • 1970-01-01
    • 2015-03-31
    • 2015-10-14
    • 1970-01-01
    • 2015-05-04
    • 1970-01-01
    • 2011-02-02
    • 1970-01-01
    相关资源
    最近更新 更多