我有一个使用javascript制作的下拉菜单,但在Firefox和Chrome中运行时它在IE中无效。我正在使用的HTML代码是:
<div id="sidemeny-container">
<div class="sidemenu-maincat">
<img src="cat1.jpg" alt="cat1" />
<div class="sidemenu-subcat hidden">
<a href="subcat1.html"> - Subcat 1 </a>
</div>
<div class="sidemenu-subcat hidden">
<a href="subcat2.html"> - Subcat 2 </a>
</div>
<div class="sidemenu-subcat hidden">
<a href="subcat3.html"> - Subcat 3 </a>
</div>
</div>
<div class="sidemenu-maincat">
<img src="cat2.jpg" alt="cat2" />
<div class="sidemenu-subcat hidden">
<a href="subcat2-1.html"> - Subcat 2-1 </a>
</div>
<div class="sidemenu-subcat hidden">
<a href="subcat2-2.html"> - Subcat 2-2 </a>
</div>
<div class="sidemenu-subcat hidden">
<a href="subcat2-3.html"> - Subcat 2-3 </a>
</div>
</div>
</div>
CSS代码:
#sidemeny-container {
border-bottom:1px #000 solid;
height: auto;
width: 153px;
float:left;
padding: 10px 0px 0px 0px;
}
.sidemenu-maincat {
border-top: 1px #000 solid;
border-right: 1px #000000 solid;
width:148px;
height:auto;
float:left;
padding: 0px 0px 0px 5px;
}
.sidemenu-subcat.hidden {
display:none;
width:148px;
height:auto;
float:left;
padding: 0px 0px 0px 15px;
}
和javascript
function initiate()
{
var sideMenuOptions = document.getElementsByClassName('sidemenu-maincat');
for (var i = 0; i < sideMenuOptions.length; i++) {
sideMenuOptions[i].addEventListener('click', function() {
var subMenuItems = this.getElementsByClassName('sidemenu-subcat');
for (var s = 0; s < subMenuItems.length; s++) {
var subItem = subMenuItems[s];
if (subItem.offsetWidth === 0 && subItem.offsetHeight === 0) {
subItem.className = 'sidemenu-subcat';
} else {
subItem.className = subItem.className + ' hidden';
}
}
});
}
}
window.onload = initiate;
我无法理解为什么这在IE中不起作用,因为它在其他浏览器中工作得很好。而且我更喜欢将我的所有javascript保存在单独的文档javascript.js中,以及我不想使用库。
答案 0 :(得分:0)
if (document.getElementsByClassName)
{
var sideMenuOptions = document.getElementsByClassName('sidemenu-maincat');
for (var i = 0; i < sideMenuOptions.length; i++) {
sideMenuOptions[i].addEventListener('click', function () {
var subMenuItems = this.getElementsByClassName('sidemenu-subcat');
for (var s = 0; s < subMenuItems.length; s++) {
var subItem = subMenuItems[s];
if (subItem.offsetWidth === 0 && subItem.offsetHeight === 0) {
subItem.className = 'sidemenu-subcat';
} else {
subItem.className = subItem.className + ' hidden';
}
}
});
}
}
else
{
var sideMenuOptions = document.getElementsByTagName('div');
for (var i = 0; i < sideMenuOptions.length; i++) {
if (sideMenuOptions[i].className == 'sidemenu-maincat')
{
sideMenuOptions[i].addEventListener('click', function () {
var subMenuItems = this.getElementsByClassName('sidemenu-subcat');
for (var s = 0; s < subMenuItems.length; s++) {
var subItem = subMenuItems[s];
if (subItem.offsetWidth === 0 && subItem.offsetHeight === 0) {
subItem.className = 'sidemenu-subcat';
} else {
subItem.className = subItem.className + ' hidden';
}
}
});
}
}
}