我正在尝试制作网页。但是旋转琴弦时遇到问题。
我想在加载页面时制作几个字符串来旋转。
如果只有一个字符串,则使用此代码可以很好地旋转。
但是当有两个或更多字符串并且我给它们相同的class
以使用等效的JavaScript代码进行旋转时,它不起作用。
它正在工作(只有第一个字符串)
<body>
<div>
<ul>
<li><span id="div" style="background-color:yellowgreen">
What to eat at Newton Food Centre</span>
</li><p>
<!--<li><span class="div" style="background-color:skyblue">the
most unique cocktails in Singapore</span></li>-->
</ul>
</div>
<script>
var div = document.getElementById("div");
var timer = setInterval("doRotate()",200);
div.onclick = function (e) {
clearInterval(timer);
}
function doRotate() {
var str = div.innerHTML;
var firstChar = str.substr(0,1);
var remains = str.substr(1, str.length-1);
str = remains + firstChar;
div.innerHTML = str;
}
</script>
</body>
这不起作用
<body>
<div>
<ul>
<li><span class="div" style="background-color:yellowgreen">
What to eat at Newton Food Centre</span></li><p>
<li><span class="div" style="background-color:skyblue">
the most unique cocktails in Singapore</span></li>
</ul>
</div>
<script>
var div = document.getElementsByClassName("div");
var timer = setInterval("doRotate()",200);
div.onclick = function (e) {
clearInterval(timer);
}
function doRotate() {
var str = div.innerHTML;
var firstChar = str.substr(0,1);
var remains = str.substr(1, str.length-1);
str = remains + firstChar;
div.innerHTML = str;
}
</script>
</body>
我想看到这两个字符串一次旋转。 请告诉我我正在制作的错误...... 谢谢!
答案 0 :(得分:1)
document.getElementsByClassName("div")
将返回许多div的对象而不是单个div,因此您需要像这样迭代它们:
var div = document.getElementsByClassName("div");
var timer = setInterval("doRotate()", 200);
for (var i = 0; i < div.length; i++) {
div[i].onclick = function(e) {
clearInterval(timer);
}
}
function doRotate() {
for (var i = 0; i < div.length; i++) {
var str = div[i].innerHTML;
var firstChar = str.substr(0, 1);
var remains = str.substr(1, str.length - 1);
str = remains + firstChar;
div[i].innerHTML = str;
}
}
&#13;
<body>
<div>
<ul>
<li><span class="div" style="background-color:yellowgreen">
What to eat at Newton Food Centre</span></li>
<p>
<li><span class="div" style="background-color:skyblue">
the most unique cocktails in Singapore</span></li>
</ul>
</div>
<script>
</script>
</body>
&#13;