我有一个按钮列表,当点击一个按钮时,该按钮的类名将更改为在屏幕上移动它并引入一个'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%;
}
答案 0 :(得分:2)
只需删除else
部分,因为它会打破循环。
for (i = 0; i < button.length; i++) {
if (button[i].classList.contains('second_pos')) {
button[i].classList.remove('second_pos');
} // else {
// return;
// }
}