猿问

带有移动文本的横幅,根据宽度自动调整 div 大小并保留主体宽度

我正在尝试制作带有移动文本的横幅。我想出了一种方法来做到这一点,但不幸的是,我的实现有两个主要问题。

  1. 我必须根据文本的长度手动调整 px 中的宽度值。

  2. 它导致车身尺寸在宽度方面更大。我希望身体保持 100%/与窗口相同的大小。

知道如何解决这两个问题,或者是否有更好的方法来实现这一点?

let txtAnnounce = document.createElement('div');

txtAnnounce.style = 'display: block; position: absolute; width: 600px; height: 45px; top: 65px; left: 0px; color: white; line-height: 45px; text-align: center;';

txtAnnounce.innerHTML = "Some text blah blah blach... Good for announcements with long text....! :) "

document.body.appendChild(txtAnnounce);


let txtAnnounce2 = document.createElement('div');

txtAnnounce2.style = 'display: block; position: absolute; width: 600px; height: 45px; top: 65px; left: 600px; color: white; line-height: 45px; text-align: center;';

txtAnnounce2.innerHTML = "Some text blah blah blach... Good for announcements with long text....! :) "

document.body.appendChild(txtAnnounce2);


let curLeft = 0;

let curLeft2 = 0;

setInterval(function() {

        curLeft--;

        curLeft2--;

        if (curLeft < -600) {

                curLeft = 0;

        }

        if (curLeft2 < 0) {

                curLeft2 = 600;

        }

        txtAnnounce.style.left = curLeft.toString() + 'px';

        txtAnnounce2.style.left = curLeft2.toString() + 'px';

}, 10);

<div id="announce" style="position: absolute; display: block; top: 65px; left: 0px; border-bottom: 1px solid #cccccc; height: 45px; width: 100%; background-color: #008aff; color: white; text-align: center; line-height: 45px; font-family: Arial, Helvetica, sans-serif;"></div>


萧十郎
浏览 151回答 1
1回答

HUX布斯

您甚至可以尝试使用 CSS 动画并根据设备的视口定义容器大小。overflow: hidden 保留公告 - 包含在公告容器中的文本。.announcement {&nbsp; background:&nbsp; #008aff;&nbsp; padding: 15px;&nbsp; color: white;&nbsp; overflow: hidden;}.announcement--text {&nbsp; position: relative;&nbsp; left: 100vw;&nbsp; white-space: nowrap;&nbsp; animation: move 10s infinite;&nbsp; animation-timing-function: linear;}@keyframes move {&nbsp; from {left: 100vw;}&nbsp; to {left: -100vw;} //maximum length of your announcement}<div class="announcement">&nbsp; <div class="announcement--text">Some text blah blah blach... Good for announcements with long text....! </div></div>
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答