简体   繁体   中英

How do I change the image in a navbar based on what the active url is?

What I'm trying to do is have #navbar-image-id2games be toggled when the active url is index.html . I attempted to do this with javascript like so, but it doesn't seem to be working.

HTML:

<div class="navbar-item" id="navbar-item-ID2Games">
                            <a href="index.html" id="index-url">
                                <div class="navbar-image" id="navbar-image-unhovered">
                                </div>
                                <div class="navbar-image" id="navbar-image-id2games">
                                </div>

                                <br>

                                <div class="navbar-text">
                                    ID2 Games
                                </div>
                            </a>
    </div>

Javascript:

$('#index-url').active(function() {
                  $('#navbar-image-id2games').toggle();
                  $('#navbar-image-unhovered').hide();
});

JSFiddle: https://jsfiddle.net/zxsmuaae/

You can check whether or not the user is at index.html by doing:

if (window.location.href.match(/index\.html/)) {
    // toggle
}

You can check the url with an if statement, and then set the visibility to hidden if it is on a certain page.

var navimg = document.getElementById("navbar-image-id2games");
if(window.location.href === "http://example/index.html"){
    navimg.style.visibility = "hidden";
}

If you want it to be reverse where it is hidden only when it is not on index.html , you can replace === with !== .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM