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

标签 javascript jquery html css svg

我想自动滚动到水平维度的中间,这样红线(就放在 svg 的中间)就在中间。

我必须为 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>

最佳答案

您应该像下面这样设置 scrollLeft 属性:

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

请看下面的演示:

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>

关于javascript - 如何自动水平滚动到div内的中间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41743389/

相关文章:

javascript - 使用 Shadow DOM 增强 SVG 标签

javascript - Highcharts 多个缺少数据点的系列

javascript - HighMaps 不显示国家数据

javascript - 10秒后刷新页面中的特定div

javascript - 如何根据输入字段数组验证禁用提交按钮

JavaScript,将对象转换为数组

JavaScript 设置其中变量的值,然后在另一个调用中检索变量的数据

javascript - 在 <td> 元素中包含 <span> 和 <br> 是一种错误的形式吗?

javascript - 在 React/Next js 中路由之前检查更改

javascript - 在 javascript 中删除 <tbody> 中的表