简体   繁体   English

在 Javascript 或 jQuery 中如何滚动以使另一个 div 内的元素垂直和水平居中

[英]In Javascript or jQuery how to scroll so that an element inside another div is centered vertically and horizontally

I'm trying to use jQuery or Javascript to auto scroll so that the .innerElement is centered vertically and horizontally in the .wrapper scroll boxes.我正在尝试使用 jQuery 或 Javascript 自动滚动,以便.innerElement.wrapper滚动框中vertically and horizontally居中。

Note that the scrollable area has to be inside of a div, it can't use the window viewport (since the final version of this will have multiple scrollable areas).请注意,可滚动区域必须在 div 内,它不能使用窗口视口(因为它的最终版本将有多个可滚动区域)。

I tried this:我试过这个:

 $('.wrapper') .scrollTop($('.innerElement').position().top - ($('.wrapper').height() / 2)) .scrollLeft($('.innerElement').position().left - ($('.wrapper').width() / 2));
 body { overflow: hidden; } .wrapper { width: 100vw; height: 100vh; overflow: auto; } .inner { width: 5000px; height: 5000px; position: relative; } .innerElement { width: 20px; height: 20px; background: #000; top: 1400px; left: 1300px; position: absolute; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="wrapper"> <div class="inner"> <div class="innerElement"></div> </div> </div>

I can't wrap my head around the math on this.我无法围绕这个数学。

I would recommend a different formula to calculate the required coords:我会推荐一个不同的公式来计算所需的坐标:

For Top offset: (ElementTop - (WrapperHeight / 2) + (ElementHeight / 2))
For Left offset: (ElementLeft - (WrapperWidth / 2) - (ElementWidth / 2))

Also you can make use of the native 'Scroll' method to achieve a smooth transition.您也可以利用原生的“滚动”方法来实现平滑过渡。

I attach a CodePen with the concept: https://codepen.io/geekzolanos-dev/pen/xxGEmRq我附上一个带有概念的 CodePen: https ://codepen.io/geekzolanos-dev/pen/xxGEmRq

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM