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

时间:2017-08-11 16:02:50

标签: javascript jquery html css horizontal-scrolling

我有一个有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>

JAVSCRIPT:

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;
}

1 个答案:

答案 0 :(得分:1)

如果您将第一行更改为var elOffset = $(id)[0].offsetLeft;,则原始代码在每种情况下都会有效。

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

相关问题