Without using the popular scrollTo plugin, how can I scroll to the vertical middle (50%) of the page/div?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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});
回答2:
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.