嗨,我有一份像这样的菜单
<div id="products_menu" class="span-9 last">
<ul>
<li><a href="#">beauty</a></li>
<li><a href="#">fragrence</a></li>
<li><a href="#">at home</a></li>
</ul>
</div>我想使用jquery根据其中一个链接的悬停来更改主div的CSS背景图像。
例如,当用户将鼠标悬停在Beauty链接上时,将css bg-imge更改为x;如果用户将鼠标悬停在fragrance上,则将css bg-image更改为y。
任何帮助都是最好的
谢谢
发布于 2011-03-04 02:56:11
坐在这里上课有点无聊,我认为如果有一个真正的解决方案而不是“添加ID”并使用通用的JQuery解决方案,对你和每个人都更有用,所以我们开始吧。
这个解决方案将允许任何大小的列表,并需要一个包含所需背景图像路径的字符串数组。该数组应该与列表线性相关,这意味着该数组应该是列表中elem 1的图像,依此类推。
现在来看代码。幸运的是,使用这个解决方案,您不需要更改任何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)")
})最后是在jsfiddle http://jsfiddle.net/k8ywX/上的概念证明。
发布于 2011-03-04 03:04:07
使用asawyer代码并对其进行修改...
$(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","");
});
});发布于 2011-03-04 04:19:47
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);
});现场演示: http://jsfiddle.net/simevidas/hcu3h/2/
https://stackoverflow.com/questions/5185067
复制相似问题