jQuery 如何滚动到页面中间(50%)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6029161/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 20:16:22  来源:igfitidea点击:

How to scroll to middle (50%) of page

jqueryscroll

提问by Steve

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

不使用流行的 scrollTo 插件,如何滚动到页面/div 的垂直中间(50%)?

回答by Bart Vangeneugden

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

这会将 div 的内部滚动滚动到它的垂直中间

var myDiv = $("#yourdiv");
var scrollto = myDiv.offset().top + (myDiv.height() / 2);
myDiv.animate({ scrollTop:  scrollto});

回答by jaheraho

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

JQuery - 跳转到滚动 div 的 vert/hori 中间

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.

用你的 div 替换“#scroll-div”。“身体”对我不起作用。

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.

那是唯一适合我的解决方案。实际上,它是一个 2h-try'n'error 解决方案,可以很好地完成它的工作。也许有人可以解释为什么 scrollTop 永远不会达到 prop("scrollheight") 的值,并且 diff 和 middle 的书面计算是必要的。