簡體   English   中英

如何水平滾動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>

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

如果將第一行更改為var elOffset = $(id)[0].offsetLeft; 然后原始代碼會在每種情況下每次都起作用。

有關更多信息,請參見以下內容: https : //javascript.info/size-and-scroll

要使其居中,您需要在黃色容器中添加一個右邊距,以“填充”右側並使其居中。 我更新了您的小提琴: 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; 每次點擊后都會更改。 我更新了小提琴以檢查偏移量是否大於容器寬度。 如果數量較少,我們將阻止更新。

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

更新:這是第一次工作,但是如果用戶滾動,計算結果將不太正確。 您應該查看https://developer.mozilla.org/zh-CN/docs/Web/API/Element/scrollWidth,以幫助計算滾動條實際可以移動多遠。 這意味着當條形圖一直向右移動以顯示所有內容時,該數字值與總寬度不同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM