原本的HTML 代码 (错的)
<div class="name_box" style="white-space: nowrap; width: 100%;"><-- 这是重点-->
<span class="companyName"> {{ item.companyName }}</span>
</div>
js 代码
leftright() {
var box = document.querySelectorAll(".name_box");
// box 是一个数组
setInterval(() => {
box.forEach((item) => {
if (
item.scrollLeft < Math.round(item.scrollWidth - item.offsetWidth)
) {
item.scrollLeft++;//主要代码
} else {
item.scrollLeft = 0;
}
});
}, 100);
},
前提是该dom的内容宽 > dom的占位宽,即 scrollWidth大于offsetWidth
出错在没给当前的dom设置overflow:auto
正确的应该是:
<div class="name_box" style="white-space: nowrap; width: 100%; overflow: auto"><--重点在这-->
<span class="companyName"> {{ item.companyName }}</span>
</div>