ScrollIntoView() causing the whole page to move

后端 未结 12 2072
庸人自扰
庸人自扰 2020-11-30 21:40

I am using ScrollIntoView() to scroll the highlighted item in a list into view. When I scroll downwards ScrollIntoView(false) works perfectly. But when I scroll upwards, Scr

12条回答
  •  长情又很酷
    2020-11-30 22:15

    You could use scrollTop instead of scrollIntoView():

    var target = document.getElementById("target");
    target.parentNode.scrollTop = target.offsetTop;
    

    jsFiddle: http://jsfiddle.net/LEqjm/

    If there's more than one scrollable element that you want to scroll, you'll need to change the scrollTop of each one individually, based on the offsetTops of the intervening elements. This should give you the fine-grained control to avoid the problem you're having.

    EDIT: offsetTop isn't necessarily relative to the parent element - it's relative to the first positioned ancestor. If the parent element isn't positioned (relative, absolute or fixed), you may need to change the second line to:

    target.parentNode.scrollTop = target.offsetTop - target.parentNode.offsetTop;
    

提交回复
热议问题