【发布时间】:2016-06-30 14:47:28
【问题描述】:
我在 jsfiddle 中有一个可以运行的脚本:https://jsfiddle.net/oxw4e5yh/
但是在 HTML 文档中它不起作用:
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
function calcSpeed(speed) {
// Time = Distance/Speed
var spanSelector = document.querySelectorAll('.marquee span'),
i;
for (i = 0; i < spanSelector.length; i++) {
var spanLength = spanSelector[i].offsetWidth,
timeTaken = spanLength / speed;
spanSelector[i].style.animationDuration = timeTaken + "s";
}
}
calcSpeed(75);
</script>
<style>
/* Make it a marquee */
.marquee {
width: 100%;
left: 0px;
height: 10%;
position: fixed;
margin: 0 auto;
white-space: nowrap;
overflow: hidden;
background-color: #000000;
bottom: 0px;
color: white;
font: 50px'Verdana';
}
.marquee span {
display: inline-block;
padding-left: 100%;
text-indent: 0;
animation: marquee linear infinite;
animation-delay: 5s;
background-color: #000000;
color: white;
bottom: 0px;
}
/* Make it move */
@keyframes marquee {
0% {
transform: translate(10%, 0);
}
100% {
transform: translate(-100%, 0);
}
}
/* Make it pretty */
.scroll {
padding-left: 1.5em;
position: fixed;
font: 50px'Verdana';
bottom: 0px;
color: white;
left: 0px;
height: 10%;
}
</style>
</head>
<body>
<div class="marquee">
<span>Lots of text, written in a long sentance to make it go off the screen. Well I hope it goes off the screen</span>
</div>
</body>
</html>
脚本是一个 css 和 javascript 字幕,用于控制滚动文本的稳定速度。
知道我错过了什么吗?
此外,正如您在小提琴中看到的那样,文本开始滚动需要一段时间。我可以减少延迟吗?
【问题讨论】:
-
当您尝试在 jsfiddle 之外使用它时,您能否更具体地说明什么不起作用?当您尝试运行控制台时,控制台是否会给您任何消息?
-
有可能你的 JavaScript 在文档准备好之前就已经运行了
-
你的小提琴在我使用时坏了。除非你期待的是一个黑色的实心大盒子
-
你在哪里执行了 javascript 代码?
-
它无法工作,因为您的脚本是在 DOM 尚未准备好时执行的,因此它正在尝试访问(尚)不存在的元素。将您的函数包装在 onload 事件中以解决问题,或者将您的脚本移动到身体的底部,尽管最佳实践是明确地包装 onload。
标签: javascript jquery html css