效果图:
1、HTML
<div class="t3"> <div id="wrapper" class="wrapper"> <div id="marquee"> <span id="marqueeContent"></span> </div> </div> </div>
2、CSS
.t3 { width: 100%; height: 50px; position: absolute; bottom: 0px; background-color: #146AA2; color: #ffffff; } .wrapper { width: 100%; display: flex; } .wrapper div { height:20px; margin-top:10px; } .wrapper span { font-size: 20px; font-weight: bold; }
3、JS
$(function () { //设置文本滑动 move(5,“left”); }) /** * 文本滑动 * @param {any} speed 时间间隔 1000 毫秒= 1 秒。 * @param {any} dic 方向 */ function move(speed, dic) { let wrapper, wrapperWidth, marquee, marqueeContent, contentWidth; wrapper = document.getElementById('wrapper'); marquee = document.getElementById('marquee'); marqueeContent = document.getElementById('marqueeContent'); contentWidth = marqueeContent.getBoundingClientRect().width; wrapperWidth = 0; if (dic == "left" || dic == "" || dic == null) { wrapperWidth = wrapper.getBoundingClientRect().width; } marquee.style.transform = 'translateX(' + wrapperWidth + 'px)'; let distance = wrapperWidth; setInterval(() => { if (dic == "left" || dic == "" || dic == null) { //当文字移动超出wrapper的左侧时 则归位 if (marquee.getBoundingClientRect().x + contentWidth < wrapper.getBoundingClientRect().x) { distance = wrapperWidth; } distance--; marquee.style.transform = 'translateX(' + distance + 'px)'; } else if (dic == "right") { //当文字移动超出wrapper的右侧时 则归位 if (marquee.getBoundingClientRect().x - contentWidth > wrapper.clientWidth) { var len = $("span[id=marqueeContent]").text().length; distance = -contentWidth / len; console.error(distance); } distance++; marquee.style.transform = 'translateX(' + distance + 'px)'; } }, speed); }