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.
精彩评论