javascript - 带移动文本的横幅,根据宽度自动调整 div 大小并保留正文宽度

标签 javascript html css

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

  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>

最佳答案

您甚至可以尝试使用 CSS 动画并根据设备的视口(viewport)定义容器大小。

overflow: hidden 保留公告——公告容器中包含的文本。

.announcement {
  background:  #008aff;
  padding: 15px;
  color: white;
  overflow: hidden;
}
.announcement--text {
  position: relative;
  left: 100vw;
  white-space: nowrap;
  animation: move 10s infinite;
  animation-timing-function: linear;
}
@keyframes move {
  from {left: 100vw;}
  to {left: -100vw;} //maximum length of your announcement
}
<div class="announcement">
  <div class="announcement--text">Some text blah blah blach... Good for announcements with long text....! </div>
</div>

关于javascript - 带移动文本的横幅,根据宽度自动调整 div 大小并保留正文宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57989310/

相关文章:

javascript - 如何在 Angularjs 中只检索可见字段值?隐藏/删除的字段在范围内持续存在

javascript - 如何使用javascript检测移动连接是2G/3G/WIFI

javascript - Mouseenter 事件正在跳过元素

javascript - 如何链接 HTML 部分?

html - 显示与文本相邻的图像时调整大小问题

php - 以 HTML 形式出现的数据直接在模式窗口中回显,但不显示在 PDF 中

javascript - 用于对数据进行排序的多个 (2) 哈希 URL 参数

javascript - 模态关闭后,vimeo 视频中的音频继续

javascript - 如何在 MouseOver 上对 CSS 动画汉堡包图标进行动画处理

html - 如何让两个子div的高度彼此相同