【问题标题】:How to automatically scroll horizontal to the middle inside a div?如何在div内自动水平滚动到中间?
【发布时间】:2017-09-20 09:04:18
【问题描述】:

我想自动滚动到水平维度的中间,这样红线(位于 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>

【问题讨论】:

    标签: javascript jquery html css svg


    【解决方案1】:

    您应该像下面这样设置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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-29
      • 2013-07-09
      • 2023-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多