简体   繁体   中英

window.location.hash not working?

I have a link ( index.html#services ) and a <div id="services> that I'm trying to change the background color of when the link is clicked and then fade back. I'm using the latest jQuery and jQuery Color plugin, and:

$(document).ready(function(){
    if(window.location.hash === '#services') {
        var service = $('#services');
        var originalColor = service.css('background-color');

        service.css('background-color', '#FFEE9F').animate({
            'background-color': originalColor
        }, 3000);
    }
});

to do the highlighting, but it's not working. Anyone know why?

That code is only run when the page is loaded, not when a link with a hash is clicked. Try following the link ( index.html#services ) directly from a new browser tab and it will probably work. What you need to do is run that code when the hash is changed. New browsers have an onhashchange event - but no such thing on older browsers. For old browsers you could poll the hash property every so often to see if it has changed.

If by chance you have a specific identifier (css class, id, name, etc.) on the links that trigger that animation, you could add a click listener to run that code. For example:

function animateBackground() {
    var service = $('#services');
    var originalColor = service.css('background-color');

    service.css('background-color', '#FFEE9F').animate({
        'background-color': originalColor
    }, 3000);
}

$(function () { // shortcut to $(document.ready)
   $('.fade-bg').live('click', animateBackground);
   animateBackground();
});

Or use

window.onhashchange = function(){
    if(window.location.hash === '#services') {
        var service = $('#services');
        var originalColor = service.css('background-color');

        service.css('background-color', '#FFEE9F').animate({
            'background-color': originalColor
        }, 3000);
    }
};

depending on which browsers you target.

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