-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 に答える