我有一个标签样式的导航菜单。我的目标:
一旦用户删除了选项卡X。将“ tabActive”类添加到选项卡X,如果该选项卡已经具有“ tabActive”类,则将其删除
显示Div“ X”
我将第二部分讲完了,我的Java代码检测到正在悬停哪个选项卡,但是我无法正确切换其他类。
到目前为止,我的代码:
的HTML
<div id="subnav">
<div id="nav1" onmouseover="toggleDisplay('contentPayment')" class="Payment myNav">
<a href="#">Payment</a></div>
<div id="nav2" onmouseover="toggleDisplay('content-shipping')" class="Shipping myNav">
<a href="#">Shipping</a></div>
<div id="nav3" class="Warranty myNav">
<a href="#">Warranty</a></div>
<div id="nav4" class="Feedback myNav">
<a href="#">Feedback</a></div>
</div>
JAVASCRIPT
<script>
var divs = new Array();
divs.push("contentPayment");
divs.push("content-shipping");
function hasClass(element, cls) {
return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;
}
function toggleDisplay(id) {
for (var i = 0; i < divs.length; i++) {
var item = document.getElementById(divs[i]);
item.style.display = 'none';
}
//Now use the passed ID to show the div you wanted to show
var target = document.getElementById(id);
target.style.display = 'block';
if (id == "contentPayment") {
var CurrentTab = document.getElementById("nav1");
var AlreadyActive = hasClass("nav1", " tabActive");
if (AlreadyActive == true) {
CurrentTab.className = "Payment myNav";
} else {
CurrentTab.className += " " + "tabActive";
}
}
}
</script>
任何想法我的问题是什么?我知道jQuery会容易得多,但是我正在为eBay编写代码,但他们不允许这样做。如何使我的tabActive类正确切换?
最佳答案
toggleDisplay
函数中有一些错误。我想您想这样做:
var divs = new Array();
divs.push("contentPayment");
divs.push("content-shipping");
function toggleDisplay(id) {
for (var i = 0; i < divs.length; i++) {
var item = document.getElementById(divs[i]);
item.style.display = divs[i] == id ? 'block' : 'none';
item.className = item.className.replace(' tabActive', '');
}
var target = document.getElementById(id);
target.className += " " + "tabActive";
}
function showAllTabs() {
for (var i = 0; i < divs.length; i++) {
var item = document.getElementById(divs[i]);
item.style.display = 'block';
item.className = item.className.replace(' tabActive', '');
}
}
当鼠标移出该选项卡时,您需要显示所有选项卡,否则您将永远无法将鼠标悬停在隐藏的选项卡上。
<div id="subnav">
<div id="contentPayment" onmouseover="toggleDisplay('contentPayment')" onmouseout="showAllTabs()" class="Payment myNav">
<a href="#">Payment</a></div>
<div id="content-shipping" onmouseover="toggleDisplay('content-shipping')" onmouseout="showAllTabs()" class="Shipping myNav">
<a href="#">Shipping</a></div>
<div id="nav3" class="Warranty myNav">
<a href="#">Warranty</a></div>
<div id="nav4" class="Feedback myNav">
<a href="#">Feedback</a></div>
</div>