我有一个按钮列表,单击其中一个按钮时,该按钮的类名将更改以在屏幕上移动它并引入一个 'back'
按钮,单击该按钮的目的是将先前单击的按钮返回到其他按钮的行,然后后退按钮再次隐藏。一切正常,但当用户单击 'back'
按钮时,单击的按钮不会返回列表。我假设 for
循环有问题,但在我看来它是有道理的。这是脚本:
//Variables
var back = document.getElementById('back');
var button = document.getElementsByTagName('li');
var i;
/*moves button that was clicked to center of page
and changes class of hidden back button to make it show*/
//works fine
function moveButton(e) {
'use strict';
var target = e.target;
target.classList.add('second_pos');
back.className = 'back';
}
//removes back button and returns active button to top
//Does remove back button but loop doesn't work on other button
function goBack() {
back.className = 'back_hidden';
for ( i = 0; i < button.length; i++) {
if (button[i].classList.contains('second_pos')) {
button[i].classList.remove('second_pos');
} else {
return;
}
}
}
//Event Listener for main buttons
for (i = 0; i < button.length; i++) {
button[i].addEventListener('click', moveButton, false);
}
// Event listener for back button
back.addEventListener('click', goBack, false);
这是CSS
.demo_space {
display:table;
position:relative;
height:100vh;
width:90%;
margin:0 auto;
ul {
display:table-cell;
height:100vh;
width:100vw;
li {
display:inline-block;
}
}
}
.first_pos {
float:left;
font-size:2em;
padding:1em;
color:$green;
}
.second_pos {
position:absolute;
bottom:50%;
left:50%;
}
最佳答案
只需删除 else
部分,因为它会中断循环。
for (i = 0; i < button.length; i++) {
if (button[i].classList.contains('second_pos')) {
button[i].classList.remove('second_pos');
} // else {
// return;
// }
}
关于javascript - 如果元素包含该名称,则使用 'for' 循环从元素中删除类名称,否则什么也不做,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40113397/