应用场景:在某一个列表中的数据指定滚动到当前日期展示,例如今天7-8,就需要将7/8这一列数据展示在最左边。
解决方法:使用Element.scrollIntoView() 方法,使用详情见MDN
Demo原图:展示不下的元素隐藏并出现滚动条,需求是:把第二个元素展示到最左侧
上代码:
<style>.container {width: 300px;height: 100px;border: 1px solid #ccc;overflow-x: scroll;white-space: nowrap;}.item {width: 100px;height: 50px;background-color: pink;display: inline-block;}</style></head><body><div class="container"><div class="item">1</div><div class="item" id="active">2</div><div class="item">3</div><div class="item">4</div></div><script>let posi = document.getElementById("active");posi.scrollIntoView({behavior: "smooth",block: "start",inline: "start"});</script></body>
此时的效果图:打开页面会自动将id为active的元素展示最左侧