简体   繁体   中英

How to use window.find() in a specific div?

我想找到一个由搜索产生的特定单词并使用window.find()滚动到它。如何在特定div而不是所有页面中使用window.find()

* This is not vanilla JavaScript *

What you should do is cache the div element in a variable and then add a function like so

(function($) {
$.fn.goTo = function() {
    $('html, body').animate({
        scrollTop: $(this).offset().top + 'px'
    }, 'fast');
    return this;
}})(jQuery);

Which can then be used by selecting your element with jQuery and will automatically focus to it. That's half of it solved for you

Next I would use something like what's used in this link to do the highlighting of the specific string highlight text tutorial .

And then the simplest part is finding the string in your div. What you would do is take the length of the string you are finding and use that value like so.

var sub = find.length //The string you are looking for
element.substring(element.indexOf(find, sub);

This is assuming your div doesn't contain child elements. Otherwise you would have to modify it to loop through the list of child elements and check each child element with the find method stated above. Not much of a change, but still a change.

  • Hope this helped

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM