我想知道简单的方法是使这个菜单动态化的最佳方法。我不想为每个元素创建一个函数。 我应该将它们推入阵列然后循环扔掉它们吗? 欢迎所有的回答和想法。
<div id="nav">
<div id="button1"></div>
<div id="button2"></div>
<div id="button3"></div>
<div id="button4"></div>
</div>
<div id="navHover">
<div id="hoverButton1"></div>
<div id="hoverButton2"></div>
<div id="hoverButton3"></div>
<div id="hoverButton4"></div>
</div>
<script type="text/javascript">
var buttonOne = document.getElementById('button1');
var buttonOneHover = document.getElementById('hoverButton1');
buttonOne.addEventListener('mouseover', buttonOneBlock, false);
buttonOne.addEventListener('mouseout', buttonOneNone, false);
buttonOneHover.addEventListener('mouseover', buttonOneBlock, false);
buttonOneHover.addEventListener('mouseout', buttonOneNone, false);
function buttonOneBlock() {
var buttonOneHover = document.getElementById('hoverButton1');
buttonOneHover.style.display = 'block';
}
function buttonOneNone() {
var buttonOneHover = document.getElementById('hoverButton1');
buttonOneHover.style.display = 'none';
}
</script>
#nav {
width: 960px;
height: 20px;
background-color: white;
margin: auto;
}
#button1, #button2, #button3, #button4 {
width: 100px;
height: 20px;
background-color: red;
float: left;
margin-left: 10px;
}
#navHover {
width: 960px;
height: 20px;
background-color: white;
margin: auto;
}
#hoverButton1, #hoverButton2, #hoverButton3, #hoverButton4 {
width: 100px;
height: 20px;
background-color: orange;
float: left;
margin-left: 10px;
display: none;
}
答案 0 :(得分:2)
这是一个直截了当的概括:
function setupButton(i) {
var button = document.getElementById('button' + i);
var buttonHover = document.getElementById('hoverButton' + i);
button.addEventListener('mouseover', buttonBlock, false);
button.addEventListener('mouseout', buttonNone, false);
buttonHover.addEventListener('mouseover', buttonBlock, false);
buttonHover.addEventListener('mouseout', buttonNone, false);
function buttonBlock() {
buttonHover.style.display = 'block';
}
function buttonNone() {
buttonHover.style.display = 'none';
}
}
for (var i = 1; i <= 4; ++i) {
setupButton(i)
}