-2

我想在一个循环中使用 2 个 addEventListeners 在导航菜单中添加和删除悬停类。

这是 CSS 和 HTML: .hovering { background-color: yellow; }

<ul>
    <li><a href="index.html" id="homeId">One</a></li>
    <li><a href="businesspage.html" id="businessId">Two</a></li>
    <li><a href="newspage.html" id="newsId">Three</a></li>  
</ul>

这是可以工作但不使用循环的 JavaScript:

/* Script 1 start */
// First item
var homePg = document.getElementById("homeId"); // The homeID is in the <a> element
var homeHover = {
    addHoverClass: function() {
        homePg.setAttribute("class", "hovering");
    },
    removeHoverClass: function() {
        homePg.removeAttribute("class");
    }
} //End homeHover object
// Activate focus event on menu 
homePg.addEventListener("mouseover", homeHover.addHoverClass, false);
homePg.addEventListener("mouseout", homeHover.removeHoverClass, false);

// Second item

var businessPg = document.getElementById("businessId");
var businessHover = {
    addHoverClass: function() {
        businessPg.setAttribute("class", "hovering");
    },
    removeHoverClass: function() {
        businessPg.removeAttribute("class");
    }

} //End hovMenu object
// Activate focus event on menu 
businessPg.addEventListener("mouseover", businessHover.addHoverClass, false);
businessPg.addEventListener("mouseout", businessHover.removeHoverClass, false);

//Third item

    var newsPg = document.getElementById("newsId");
    var newsHover = {
        addHoverClass: function() {
            newsPg.setAttribute("class", "hovering");
        },
        removeHoverClass: function() {
            newsPg.removeAttribute("class");
        }

    } //End hovMenu object
    // Activate focus event on menu 
    newsPg.addEventListener("mouseover", newsHover.addHoverClass, false);
    newsPg.addEventListener("mouseout", newsHover.removeHoverClass, false);


 /* End Script 1 */

当我使用脚本 2 时,只有最后一项正确悬停。任何帮助表示赞赏。谢谢

 /* Script 2 start */
var gbotNav = [ "homePg", "businessPg", "newsPg" ];
var gbotId = [ "homeId", "businessId", "newsId" ];
var gbotHov = [ "homeHover", "businessHover", "newsHover"];
var count = gbotNav.length;

for (var i = 0; i < count; i = i + 1) {
var myGbotNav = gbotNav[i];
var myGbotHov = gbotHov[i];
var myGbotId = gbotId[i];

var myGbotNav = document.getElementById( myGbotId );
var myGbotHov = {
        addHoverClass: function() {
            myGbotNav.setAttribute("class", "hovering");
        },
        removeHoverClass: function() {
            myGbotNav.removeAttribute("class");
        }
    } //End gbotHov object
// Activate focus event on menu 
myGbotNav.addEventListener("mouseover", myGbotHov.addHoverClass, false);
myGbotNav.addEventListener("mouseout", myGbotHov.removeHoverClass, false);

} /* End for loop */
/* End Script 2 */
4

1 回答 1

0

您是否尝试过使用 CSS :hover 伪类?

http://www.w3schools.com/cssref/sel_hover.asp

于 2013-03-20T00:22:43.560 回答