我有三个带有'拇指'类的div,它们用于选择产品。我目前正在使用以下代码来突出显示当前的选择:
$('.thumbs').hover(function(){
$(this).stop().fadeTo("normal", 1.0);
},function(){
$(this).stop().fadeTo("slow", 0.5);
});
默认情况下,所有选项均为50%不透明度,当您将鼠标悬停在选项上时,它会淡化为100%不透明度,当您移动鼠标时,它将返回到50%。问题是我希望它在单击选项时保持100%,然后在悬停时仅更改其他2个选项。然后当另一个选项是点击时,我希望它变为100%不透明度而其他选项返回到50%。我希望自己能够很好地解释自己,如果不随意发表评论。任何帮助将不胜感激。
答案 0 :(得分:1)
$(window).bind("load", function() {
var activeOpacity = 1.0,
inactiveOpacity = 0.5,
fadeTime = "slow",
clickedClass = "selected",
thumbs = ".thumbs";
$(thumbs).hide();
$(thumbs).fadeTo(1, inactiveOpacity);
$(thumbs).hover(
function(){
$(this).fadeTo(fadeTime, activeOpacity);
},
function(){
// Only fade out if the user hasn't clicked the thumb
if(!$(this).hasClass(clickedClass)) {
$(this).fadeTo(fadeTime, inactiveOpacity);
}
});
$(thumbs).click(function() {
// Remove selected class from any elements other than this
var previous = $(thumbs + '.' + clickedClass).eq();
var clicked = $(this);
if(clicked !== previous) {
previous.removeClass(clickedClass);
}
clicked.addClass(clickedClass).fadeTo(fadeTime, activeOpacity);
});
});
我认为这会有所帮助。我遇到了同样的问题,Stackoverflow的某个人为我制作了这个脚本。它完美无缺! (我编辑了一些东西......)
答案 1 :(得分:1)
这可能是一个更简单的解决方案:
jQuery(function($) {
// Save off an "active" variable that will be available
// throughout this block
var active;
// When you click on a thumb, remember that you did so
$(".thumbs").click(function() {
$(this).data("clicked", true);
});
$(".thumbs").hover(function() {
// If the current thumb is the active thumb (because it was
// previously clicked, the user hovered out and is now hovering
// back in), do nothing.
if(this == active[0]) return;
// Otherwise, stop the active thumb, slowly fade it out, and,
// if it had been clicked, forget that fact.
active.stop().fadeTo("slow", 0.5).removeData("clicked");
// Set the current thumb to "active", stop its animation, then
// fade it to full.
active = $(this).stop().fadeTo("normal", 1.0);
},function(){
// When hovering out, fade it down to 0.5 unless it had been
// clicked, in which case do nothing.
if(!$(this).data("clicked")) $(this).stop().fadeTo("slow", 0.5)
});
});
这里的技巧是使用$().data()
和闭包来存储活动的拇指。