搜索网站上的文字

Fre*_*cer 5 html javascript web-applications

尊敬的会员,

我在一个模板的帮助下用纯HTML设计网站.

在那我有一个文本框[搜索]和Go按钮.

我想进行操作,以便当任何人键入某些文本并按下Go按钮时,它应突出显示该网站中与该文本匹配的文本.

我怎样才能做到这一点?

比你.

amr*_*neo 11

$(document).ready(function(){
        $('#searchItem').keyup(function(){
            var name = $(this).val();
            var pattern = name.toLowerCase(); 
            var targetId = ""; 
            var divs = document.getElementsByClassName("item"); 

            $(document).find('.item').hide();

            $('.item').each(function(i){
                var para = divs[i].getElementsByTagName("p"); 
                var index = para[0].innerText.toLowerCase().indexOf(pattern); 
                if (index != -1) { 
                    $(this).show();
                }
            });
        }); 
    });
Run Code Online (Sandbox Code Playgroud)

  • 我不确定这是如何工作的.实际的html标签对用户不可见,但如果我们使用它,将会返回.例如:var position = document.documentElement.innerHTML.indexOf('<p>'); 将返回一个有效的索引,但网页中的用户实际上看不到 (3认同)

Viv*_*gon 5

你没有张贴你的东西.我想这就是你提到的.

检查一下.我可以为你做这件事,但你必须在你的想法中做到这一点

function highlightInElement(elementId, text){
var elementHtml = document.getElementById(elementId).innerHTML;
var tags = [];
var tagLocations= [];
var htmlTagRegEx = /<{1}\/{0,1}\w+>{1}/;

//Strip the tags from the elementHtml and keep track of them
var htmlTag;
while(htmlTag = elementHtml.match(htmlTagRegEx)){
    tagLocations[tagLocations.length] = elementHtml.search(htmlTagRegEx);
    tags[tags.length] = htmlTag;
    elementHtml = elementHtml.replace(htmlTag, '');
}

//Search for the text in the stripped html
var textLocation = elementHtml.search(text);
if(textLocation){
    //Add the highlight
    var highlightHTMLStart = '<span class="highlight">';
    var highlightHTMLEnd = '</span>';
    elementHtml = elementHtml.replace(text, highlightHTMLStart + text + highlightHTMLEnd);

    //plug back in the HTML tags
    var textEndLocation = textLocation + text.length;
    for(i=tagLocations.length-1; i>=0; i--){
        var location = tagLocations[i];
        if(location > textEndLocation){
            location += highlightHTMLStart.length + highlightHTMLEnd.length;
        } else if(location > textLocation){
            location += highlightHTMLStart.length;
        }
        elementHtml = elementHtml.substring(0,location) + tags[i] + elementHtml.substring(location);
    }
}

//Update the html of the element
document.getElementById(elementId).innerHTML = elementHtml;
}

highlightInElement("fatDoggie","The dog is really really fat");
Run Code Online (Sandbox Code Playgroud)

这个小提琴是为了突出显示一组文本而不是你应该在搜索中获取变量并放置在 highlightInElement("Element","Var");