更改除选定元素之外的所有元素的不透明度

时间:2011-04-06 14:53:02

标签: javascript jquery css opacity

我在一个页面上有三个图像,我想淡出未点击的元素。该脚本在第一个实例中工作,因此如果您单击一张图片,则另外两个淡出。如果您认为点击已经褪色的图片,那么所有发生的事情都是最后一个非褪色的图片也会消失,而不是100%不透明而其他两个褪色。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<style>
.opac {
        filter:alpha(opacity=50);
        -moz-opacity:0.5;
        -khtml-opacity: 0.5;
        opacity: 0.5;
        border:thick;
}
</style>
<script>
$(document).ready(function(){
    $('a.images').click(function()
    {
        $(this).siblings().stop().animate({opacity: 0.4}, 300);
        $('a.images').click(function()
        {
            $not('this').stop().animate({opacity: 1.0}, 300);
    });
});
});
</script>






</head>


html

    <body>
        <div id="images">
        <a class="images" href="#"><img class="click" src="../appalachia.jpg" height="133" /><br/><br/></a>
        <a class="images" href="#"><img class="click" src="../appalachia.jpg" height="133" /><br/><br/></a>
        <a class="images" href="#"><img class="click" src="../appalachia.jpg" height="133" /><br/><br/></a>
        </div>

        </body>

    </html>

2 个答案:

答案 0 :(得分:5)

您正在click处理程序中附加click处理程序。每次单击时,都会添加一个新的单击处理程序,并在每次后续单击时调用。

使用最新添加的名为first的调用点击处理程序,这意味着最后,所有图像都设置为透明。

如果您希望所点击的图片不透明,而其他图片透明,请尝试以下操作:

$('a.images').click(function(){
    // Make all images (except this) transparent
    $('a.images').not(this).stop().animate({opacity: 0.4}, 300);
    // Make this opaque
    $(this).stop().animate({opacity: 1.0}, 300);
});

演示:http://jsfiddle.net/gCsRL/1/

答案 1 :(得分:4)

在此代码中:

$('a.images').click(function() {
    $(this).siblings().stop().animate({opacity: 0.4}, 300);
    $('a.images').click(function() {
        $not('this').stop().animate({opacity: 1.0}, 300);
    });
});

每次点击都会反复注册点击处理程序。试试这个:

$('a.images').click(function() {
    $(this).siblings().stop().animate({opacity: 0.4}, 300);
    $(this).stop().animate({opacity: 1.0}, 300);
});
相关问题