简体   繁体   English

如何自动水平滚动到div内的中间?

[英]How to automatically scroll horizontal to the middle inside a div?

I want to automatically scroll to the middle in the horizontal dimension, such that the red line (which is placed right in the middle of the svg) is in the middle.我想自动滚动到水平尺寸的中间,这样红线(位于 svg 的中间)在中间。

Which values do I have to choose for scrollLeft ?我必须为scrollLeft选择哪些值?

 var div = $('.container'); div.animate({ scrollLeft: div.width() / 2 + div.offset().left });
 .container { height: 200px; width: 400px; border: 1px solid black; overflow: scroll; margin-left: 50px; }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class=container> <svg width="1000" height="400"> <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" /> <circle cx="200" cy="200" r="40" stroke="green" stroke-width="4" fill="yellow" /> <circle cx="600" cy="200" r="40" stroke="green" stroke-width="4" fill="yellow" /> <circle cx="40" cy="320" r="40" stroke="green" stroke-width="4" fill="yellow" /> <circle cx="960" cy="320" r="40" stroke="green" stroke-width="4" fill="yellow" /> <line x1="499" y1="0" x2="499" y2="400" style="stroke:rgb(255,0,0);stroke-width:2" /> </svg> </div>

You should be setting the scrollLeft property like below:您应该像下面这样设置scrollLeft属性:

div.find('svg').width() / 2 - div.width() / 2

See demo below:请参阅下面的演示:

 var div = $('.container'); div.animate({ scrollLeft: div.find('svg').width() / 2 - div.width() / 2 });
 .container { height: 200px; width: 400px; border: 1px solid black; overflow: scroll; margin-left: 50px; }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class=container> <svg width="1000" height="400"> <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" /> <circle cx="200" cy="200" r="40" stroke="green" stroke-width="4" fill="yellow" /> <circle cx="600" cy="200" r="40" stroke="green" stroke-width="4" fill="yellow" /> <circle cx="40" cy="320" r="40" stroke="green" stroke-width="4" fill="yellow" /> <circle cx="960" cy="320" r="40" stroke="green" stroke-width="4" fill="yellow" /> <line x1="499" y1="0" x2="499" y2="400" style="stroke:rgb(255,0,0);stroke-width:2" /> </svg> </div>

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

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