Does scrollIntoView work in all browsers?

前端 未结 6 480
不思量自难忘°
不思量自难忘° 2020-11-29 00:46

Does scrollIntoView() work in all browsers? If not is there a jQuery alternative?

相关标签:
6条回答
  • 2020-11-29 01:20

    You can use jQuery alternative and animate <html> and <body> elements:

    $('html, body').animate({
      scrollTop: $("#myElem").offset().top
    }, 1000);
    
    0 讨论(0)
  • 2020-11-29 01:28

    Have not tried this, but seems like piggybacking on built in scrollIntoView function would save much code. Here is what I would do if you want animated action:

    1. Cache current scroll position of the container as START POSITION
    2. run built in scrollIntoView
    3. Cache the scroll position again as the END POSITION
    4. Return container back to START POSITION
    5. Animate scrolling to END POSITION
    0 讨论(0)
  • 2020-11-29 01:37

    read please about scrollIntoViewIfNeeded

    if(el.scrollIntoViewIfNeeded){
    el.scrollIntoViewIfNeeded()
    }else{
    el.scrollIntoView()
    }
    
    0 讨论(0)
  • 2020-11-29 01:38

    I use Matteo Spinnelli's iScroll-4 and it works in iOS safari as well. It has three methods scrollTo, scrollToElement and scrollToPage. Let's say you have an unordered list of elements wrapped inside a div. As Robert Koritnik has written above, you need to have that slight animation to show that you have scrolled. The below method achieves that effect.

    scrollToElement(element, time); 
    
    0 讨论(0)
  • 2020-11-29 01:44

    Looks like it does: http://www.quirksmode.org/dom/w3c_cssom.html

    0 讨论(0)
  • 2020-11-29 01:46

    It is supported yes, but user experience is... bad.

    As @9bits pointed out, this has long been supported by all major browsers. Not to worry about that. The main problem is the way that it works. It simply jumps to a particular element that may as well be at the end of the page. By jumping to it, users have no idea whether:

    • page has been scrolled up
    • page has been scrolled down
    • they've been redirected elsewhere

    The first two can be determined by scroll position, but who says users kept track of scroll position before jump was done? So it's an nondeterministic action.

    The last one may be true especially if the page has moving header that gets scrolled out of view and remaining page design doesn't imply anything on being on the same page (if it also doesn't have any total height vertical element like left menu bar). You'd be surprised how many pages have this problem. just check them out yourself. Go to some page, look at it at top, then press End key and look at it again. It is likely that you'll think it's a different page.

    Animated scrollintoview jQuery plugin to the rescue

    That's why there still are plugins that perform scroll into view instead of using native DOM function. They usually animate scrolling which eliminates all 3 issues outlined above. Users can easily keep track of the movement.

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