I'm looking for something similar to this: Active navigation with jQuery - can't apply a default class to anchor
But I'm using images inside a unordered list and I want to detect the current URL and append the img src with _over.jpg to show it开发者_开发知识库 being the current page. (no lectures on using BG position please - the client likes this.)
I'm also using this easy hover (jQuery mouseover), which I bet will need to be adjusted...
$(document).ready(function(){
$(".navbar li").each(function(){
var link = $(this).children("a");
var image = $(link).children("img");
var imgsrc = $(image).attr("src");
// add mouseover
$(link).mouseover(function(){
var on = imgsrc.replace(/.jpg$/gi,"_over.jpg");
$(image).attr("src",on);
});
// add mouse out
$(link).mouseout(function(){
$(image).attr("src",imgsrc);
});
});
});
The magic is in document.location.pathname :P
$(document).ready(function(){
$(".navbar li").each(function(){
var link = $(this).children("a");
var image = $(link).children("img");
var imgsrc = image.attr("src"); //no need to rewrap in $
var on = imgsrc.replace(/.jpg$/gi,"_over.jpg");
if (link.attr("href") == document.location.pathname || link.attr("href") == document.location.href)
$(image).attr("src",on);
else
// add mouseover
$(link).hover(function(){
$(image).attr("src",on);
}, function(){
$(image).attr("src",imgsrc);
});
});
});
Why two conditions ORed in the if? Internet Explorer will return hostname (document.location.href) and Firefox/WebKit will return exactly what’s written on your link. But I would test for cross-browser issues if I was you.
精彩评论