JQuery Select 1st, 2nd & Third Link in LI
Hi Have a menu which look like this
<div id="products_menu" class="span-9 last">
<ul>
<li><a href="#">beauty</a></li>
<li><a href="#">fragrence</a></li>
<li><a h开发者_C百科ref="#">at home</a></li>
</ul>
</div>
I would like to use jquery to change the CSS background image of the main div based on the hover of one of the links.
for example when a user hovers over the Beauty link then change the css bg-imge to x and if the user hovers over fragrance then chaneg the css bg-image to y.
Any help would be great
Thanks
Sitting here in class kinda bored I decided it would be more useful to you and everyone if there was a real solution rather than the "Add an ID" and use common JQuery solution so here we go.
This solution will allow any size list and requires an array of strings that contain the path to your desired background images the array should linearly relate the list meaning the array[0] should be the image for elem 1 in the list and so on.
now for the code. Lucky for you with this solution you do not have to change any html.
var backgroundImages = ["path_to_bg_1", "path_to_bg_2", "path_to_bg_3", "path_to_bg_4"];
$("#products_menu li").hover(function () {
$("#products_menu").css("background", "url("+backgroundImages[$(this).index()]+")")
}, function () {
$("#products_menu").css("background", "url(PATH_TO_DEFAULT)")
})
and finally a proof of concept at jsfiddle http://jsfiddle.net/k8ywX/
Using asawyer code and modifying it...
$(document).ready(function () {
var backgrounds = ["background1","background2","background3"];
$("#products_menu ul li").hover(
function(){
var ind = $("#products_menu ul li").index(this);
$(this).parent().parent().css({"background-image" : "url("+backgrounds[ind]+")"});
},
function (){
$(this).parent().parent().css("background","");
});
});
HTML:
<div id="products_menu" class="span-9 last">
<ul>
<li><a href="#" data-bgcolor="orange">beauty</a></li>
<li><a href="#" data-bgcolor="yellow">fragrence</a></li>
<li><a href="#" data-bgcolor="pink">at home</a></li>
</ul>
</div>
JavaScript:
$('a', '#products_menu').bind('mouseenter mouseleave', function(e) {
var c = e.type == 'mouseenter' ? $(this).data('bgcolor') : '';
$(this).closest('div').css('background-color', c);
});
Live demo: http://jsfiddle.net/simevidas/hcu3h/2/
try something like this:
<div id="products_menu" class="span-9 last">
<ul>
<li class="a"><a href="#">beauty</a></li>
<li class="b"><a href="#">fragrence</a></li>
<li class="c"><a href="#">at home</a></li>
</ul>
</div>
<script>
$("li.a").hover(function(){
$("#products_menu").css("background-image", "url(/myimage.jpg)");
});
$("li.b").hover(function(){
$("#products_menu").css("background-image", "url(/myimage1.jpg)");
});
$("li.c").hover(function(){
$("#products_menu").css("background-image", "url(/myimage2.jpg)");
});
</script>
精彩评论