How to scroll to an element in jQuery?

后端 未结 9 1683
无人及你
无人及你 2020-11-30 19:23

I have done the following code in JavaScript to put focus on the particular element (branch1 is a element),

document.location.href=\"#branch1\";


        
相关标签:
9条回答
  • 2020-11-30 19:47

    Like @user293153 I only just discovered this question and it didn't seem to be answered correctly.

    His answer was best. But you can also animate to the element as well.

    $('html, body').animate({ scrollTop: $("#some_element").offset().top }, 500);
    
    0 讨论(0)
  • 2020-11-30 19:48

    For the focus() function to work on the element the div needs to have a tabindex attribute. This is probably not done by default on this type of element as it is not an input field. You can add a tabindex for example at -1 to prevent users who use tab to focus on it. If you use a positive tabindex users will be able to use tab to focus on the div element.

    Here an example: http://jsfiddle.net/klodder/gFPQL/

    However tabindex is not supported in Safari.

    0 讨论(0)
  • 2020-11-30 19:50

    Check jQuery.ScrollTo, I think that's the behavior that you want, check the demo.

    0 讨论(0)
  • 2020-11-30 19:52

    Use

    $(window).scrollTop()

    It'll scroll the window to the item.

     var scrollPos =  $("#branch1").offset().top;
     $(window).scrollTop(scrollPos);
    
    0 讨论(0)
  • 2020-11-30 19:56

    For my problem this code worked, I had to navigate to an anchor tag on page load :

    $(window).scrollTop($('a#captchaAnchor').position().top);
    

    For that matter you can use this on any element, not just an anchor tag.

    0 讨论(0)
  • 2020-11-30 19:59

    You can extend jQuery functionalities like this:

    jQuery.fn.extend({
    scrollToMe: function () {
        var x = jQuery(this).offset().top - 100;
        jQuery('html,body').animate({scrollTop: x}, 500);
    }});
    

    and then:

    $('...').scrollToMe();
    

    easy ;-)

    0 讨论(0)
提交回复
热议问题