我是jQuery的新手,当我将鼠标悬停在剩余的缩略图上时,我将其编码为淡出三个缩略图。它看起来很混乱,我很想知道是否有一种方法可以用更清晰的方式对其进行编码,以提高我对选择器和标识符的了解。非常感谢任何发帖的人!
<script type="text/javascript">
$(function() {
$(".christmas-list-1,").css("opacity","1.0");
$(".christmas-list-1").hover(
function () {
$(".christmas-list-2,.christmas-list-3,.christmas-list-4").stop().animate({ opacity: 0.5 }, "fast");
},
function () {
$(".christmas-list-2,.christmas-list-3,.christmas-list-4").stop().animate({ opacity: 1.0 }, "fast");
}
);
$(".christmas-list-2,").css("opacity","1.0");
$(".christmas-list-2").hover(
function () {
$(".christmas-list-1,.christmas-list-3,.christmas-list-4").stop().animate({ opacity: 0.5 }, "fast");
},
function () {
$(".christmas-list-1,.christmas-list-3,.christmas-list-4").stop().animate({ opacity: 1.0 }, "fast");
}
);
$(".christmas-list-3,").css("opacity","1.0");
$(".christmas-list-3").hover(
function () {
$(".christmas-list-1,.christmas-list-2,.christmas-list-4").stop().animate({ opacity: 0.5 }, "fast");
},
function () {
$(".christmas-list-1,.christmas-list-2,.christmas-list-4").stop().animate({ opacity: 1.0 }, "fast");
}
);
$(".christmas-list-4,").css("opacity","1.0");
$(".christmas-list-4").hover(
function () {
$(".christmas-list-1,.christmas-list-2,.christmas-list-3").stop().animate({ opacity: 0.5 }, "fast");
},
function () {
$(".christmas-list-1,.christmas-list-2,.christmas-list-3").stop().animate({ opacity: 1.0 }, "fast");
}
);
});
</script>
答案 0 :(得分:6)
不要给它们单独的类名,只需对所有4使用.christmas-list
:
$(".christmas-list").css("opacity","1.0").hover(function() {
$(this).siblings(".christmas-list").stop().animate({opacity: 1.0}, "fast");
}, function() {
$(".christmas-list").stop().animate({opacity: 1.0}, "fast");
});
答案 1 :(得分:2)
$(function() {
var elms = ".christmas-list-1, .christmas-list-2, .christmas-list-3, .christmas-list-4";
$(elms).css("opacity", "1").hover(
function () { $(elms).not($(this)).stop().animate({ opacity: .5 }, "fast"); },
function () { $(elms).not($(this)).stop().animate({ opacity: 1 }, "fast"); }
);
});
答案 2 :(得分:0)
您是否考虑过使用fadeOut http://api.jquery.com/fadeOut/和for循环。
答案 3 :(得分:0)
您多次致电$
函数。尽量避免它(阅读this article的第4点)。
我认为你可以这样做:
<script type="text/javascript">
$(function() {
var arrJChr = {};
for(i=1;i<=4;i++){
arrJChr[i] = $(".christmas-list-"+i);
}
var animateFun = function(idNot, nOpacity){
for(i=1;i<=4;i++){
if(i!=idNot){
arrJChr[i].stop().animate(
{ opacity: nOpacity },
"fast"
);
}
}
};
for(i=1;i<=4;i++){
arrJChr[i].css("opacity","1.0");
arrJChr[i].hover(function(){
animateFun(i,0.5);
},function(){
animateFun(i,1.0);
});
}
});
</script>