如何水平滚动 DIV 到容器中心?

How to scroll DIV horizontally to center of container?

我有一个装有 2 DIV 的容器。当我单击一个按钮时,我试图将黄色 DIV 在容器中水平居中。但是,如果我多次单击按钮,它会来回滚动,如果我手动滚动容器然后单击按钮,黄色 DIV 永远不会滚动到视图中。

这是 jsfiddle。如果您一遍又一遍地单击该按钮,它将来回滚动。为什么这样做?: https://jsfiddle.net/nug4urna/

HTML:

<div id='container'>
<div id='blue'></div>
<div id='yellow'></div>
</div>
<div id='mybutton'>
click to scroll yellow div into view
</div>
<div id='log'>
</div>

脚本:

function scrollDivIntoView(id) {
      var elOffset = $(id).offset().left;
      var elWidth = $(id).width();
      var containerWidth = $('#container').width();
      var offset = elOffset - ((containerWidth - elWidth) / 2);

      $('#container').scrollLeft(offset);

      var _log = 'elOffset = ' + elOffset + '<br>';
      _log += 'elWidth = ' + elWidth + '<br>';
      _log += 'containerWidth = ' + containerWidth + '<br>';
      _log += 'offset = ' + offset;

      $('#log').html(_log);
}

$(document).ready(function() { 
    $('body').on('click', '#mybutton', function(){ 
        scrollDivIntoView('#yellow');
    }); 
});

CSS:

#container{
  width:100%;
  height:150px;
  border:1px solid red;
  display:inline-block;
  white-space:nowrap;
  overflow-y:hidden;
  overflow-x:auto;
}
#blue{
  width:2000px;
  height:100px;
  background-color: blue;
  margin:5px;
  display:inline-block;
}
#yellow{
  width:200px;
  height:100px;
  background-color: yellow;
  margin:5px;
  display:inline-block;
}
#mybutton{
  margin-top:10px; 
  cursor:pointer;
  background-color:black;
  color:white;
  width:400px;
  padding:4px;
  text-align:center;
}

要使其居中,您需要在 "pad" 右侧的黄色容器中添加右边距并使其居中。我更新了你的 fiddle: https://jsfiddle.net/nug4urna/2/

#yellow{
  width:200px;
  height:100px;
  background-color: yellow;
  margin:5px;
  display:inline-block;
  margin-right: 100%;
}

还有它来回跳转的原因是因为计算是基于每次点击后变化的var elOffset = $(id).offset().left;。我更新了 fiddle 以检查偏移量是否大于容器宽度。如果小于,我们将阻止更新。

  if (elOffset > containerWidth) {
    $('#container').scrollLeft(offset);
  }

更新: 这第一次有效,但如果用户滚动计算则不太正确。您应该查看 https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollWidth 以帮助计算滚动条实际可以移动多远。这意味着当条一直向右移动以显示所有内容时,数值与总宽度不同。

如果您将第一行更改为 var elOffset = $(id)[0].offsetLeft;,那么原始代码在任何情况下都能正常工作。

有关详细信息,请参阅以下内容: https://javascript.info/size-and-scroll