我在固定宽度内有一条水平滑动的元素线,因此您必须左右滚动才能看到所有元素。参见 JS Fiddle和下面的纯文本示例。
Hi | Hello | How do you do | Fine thanks | Good weather this time of year
我的问题是:如何居中给定元素水平?例如。将3号元素的水平中心放在周围div的水平中心。
如果元素不能居中,例如因为它在行的开头,没关系,那么 H 位置应该简单地为 0。它应该尽可能地居中可以 是。
最佳答案
是这样的吗?您可以组合使用以下 native 属性 scrollLeft
、offsetLeft
和 offsetWidth
。
var items = document.querySelectorAll('.wrapper ul li');
function centerItems(which) {
var wrapper = items[which].offsetParent;
wrapper.scrollLeft =
(items[which].offsetLeft + items[which].offsetWidth / 2)
- wrapper.offsetWidth / 2;
}
html {
background: #eee;
}
body {
width: 320px;
background: white;
font-family: sans-serif;
}
.wrapper {
overflow-x: scroll;
position: relative;
}
ul {
white-space: nowrap;
}
li {
display: inline-block;
color: #898;
background: #efe;
padding: 8px;
}
<p>Hello!</p>
<button onclick="centerItems(0)">1</button>
<button onclick="centerItems(1)">2</button>
<button onclick="centerItems(2)">3</button>
<button onclick="centerItems(3)">4</button>
<button onclick="centerItems(4)">5</button>
<div class="wrapper">
<ul>
<li>Short</li>
<li>Very long line here</li>
<li>Medium line</li>
<li>Another one Another one Another one</li>
<li>Yet another</li>
</ul>
</div>
<p>Goodbye!</p>
关于javascript - 将任何元素置于水平滑动线上居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35631599/