How to scroll to middle (50%) of page

2019-06-25 01:23发布

Without using the popular scrollTo plugin, how can I scroll to the vertical middle (50%) of the page/div?

标签: jquery scroll
2条回答
Root(大扎)
2楼-- · 2019-06-25 01:59

This scrolls the internal scroll of a div to it's vertical middle

var myDiv = $("#yourdiv");
var scrollto = myDiv.offset().top + (myDiv.height() / 2);
myDiv.animate({ scrollTop:  scrollto});
查看更多
聊天终结者
3楼-- · 2019-06-25 02:01

JQuery - jump to vert/hori middle of scroll-div

vertical

$("#centralize-ver").click(function(){//centralize vertical
    var scrollableDivJ=$("#scroll-div");
    scrollableDivJ.scrollTop("1000000");//scroll to max
    var scrollHeight=scrollableDivJ.prop("scrollHeight");
    var diff=(scrollHeight-scrollableDivJ.scrollTop())/2;
    var middle=scrollHeight/2-diff;
    scrollableDivJ.scrollTop(middle);
});

horizontal

$("#centralize-hor").click(function(){//centralize horizontal
    var scrollableDivJ=$("#scroll-div");
    scrollableDivJ.scrollLeft("1000000");//scroll to max
    var scrollWidth=scrollableDivJ.prop("scrollWidth");
    var diff=(scrollWidth-scrollableDivJ.scrollLeft())/2;
    var middle=scrollWidth/2-diff;
    scrollableDivJ.scrollLeft(middle);
});

Replace "#scroll-div" with your div. "body" isn't working for me.

jsfiddle

Thats the only solution that works properly for me. Actually its an 2h-try'n'error solution thats do its job pretty well. Maybe someone could explain why scrollTop is never reaching the value of prop("scrollheight") and the written calculation of diff and middle is necessary.

查看更多
登录 后发表回答