[英]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.