【问题标题】:Change opacity of 2 items on hover在悬停时更改 2 个项目的不透明度
【发布时间】:2011-09-16 08:26:53
【问题描述】:

我的页面上有 2 张图片。当我将鼠标悬停在 img.a 上时,它会将不透明度更改为 0,并且效果很好。但是,当 img.a 悬停在上方时,我希望 img.c 也将不透明度更改为 0。我的代码适用于 img.a,但不适用于 img.c

<script type='text/javascript'>
$(document).ready(function(){
$("img.a").hover(
function() {
$(this).stop().animate({"opacity": "0"}, "slow");
},
function() {
$(this).stop().animate({"opacity": "1"}, "slow");
},
function() {
$("img.c").stop().animate({"opacity": "0"}, "slow");
},
function() {
$("img.c").stop().animate({"opacity": "1"}, "slow");
});

});
</script>

【问题讨论】:

    标签: jquery hover opacity


    【解决方案1】:

    问题在于你的语法。

    jQuery 的 hover() 函数只有两个参数——这两个函数。第一个是鼠标悬停在元素上时调用的,另一个是鼠标移出时调用的。

    你快到了,现在你需要做的就是将 4 个函数组合成两个函数,它就会工作:

    <script type='text/javascript'>
    $(document).ready(function(){
    
      $("img.a").hover(
    
        function() { // this function is called on mouseover img.a
            $(this).stop().animate({"opacity": "0"}, "slow");
            $("img.c").stop().animate({"opacity": "0"}, "slow");
        },
        function() { // this function is called on mouseout img.a
            $(this).stop().animate({"opacity": "1"}, "slow");
            $("img.c").stop().animate({"opacity": "1"}, "slow");
        }
    
      });
    
    });
    </script>
    

    【讨论】:

      【解决方案2】:

      您可以使用$("img.a, img.c") 作为悬停功能中的选择器,而不是使用$(this)

      有关基本示例,请参阅 this fiddle

      【讨论】:

        【解决方案3】:

        将所有应该褪色的图像归为同一类。 然后将所有应该一起淡出的图像都赋予相同的data-group

        <img class="fade" data-group="a" />
        <img class="fade" data-group="b" />
        <img class="fade" data-group="a" />
        
        <script type="text/javascript">
        $(function(){ /* shorthand for $(document).ready(function(){ */
        
            $('img.fade').hover(function(){
        
                $('img.fade[data-group="'+$(this).data('group')+'"]').stop().animate({"opacity": "0"},"slow");
        
            },function(){
        
                $('img.fade[data-group="'+$(this).data('group')+'"]').stop().animate({"opacity": "1"},"slow");
        
            });    
        
        });
        </script>
        

        现在,当您将鼠标悬停在其中一张图片上时,同一组中的所有图片都会淡出。

        这是我在 jsFiddle 上的示例:http://jsfiddle.net/Rv9jU/

        【讨论】:

          【解决方案4】:
          $(function () {
              $("#image1").css("opacity", 0.3);
              $("#image1").hover(function () {
                  $(this).animate({ opacity: 1.0 }, 500);
              }, function () {
                  $(this).animate({ opacity: 0.3 }, 500);
              });
          })
          

          在 html 页面的脚本标签中使用这个函数有部分:

          See Example on my blog...

          【讨论】:

            猜你喜欢
            • 2013-09-11
            • 2017-06-10
            • 2015-01-04
            • 2014-02-20
            • 1970-01-01
            • 2015-12-23
            • 2021-03-05
            • 2014-06-25
            • 2013-07-28
            相关资源
            最近更新 更多