如何在jQuery中切换图像的淡出/淡出效果?

How do I switch the fadeIn/fadeOut effect on an image in jQuery?

本文关键字:淡出 图像 jQuery      更新时间:2023-09-26

我已经把这个工作到'almost ready'状态:http://jsbin.com/icuvit

谁能告诉我如何解决这个问题,所以如果我悬停它变暗,而不是在第一个实例是黑暗的。所以它从正常到>暗

我在下面的js代码中改变什么?

<!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" xml:lang="en" lang="en">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<style>
  article, aside, figure, footer, header, hgroup, 
  menu, nav, section { display: block; }
</style>
</head>
<body>  
  <div id="mask-div"></div>
  <img id="test-img" src="http://www.google.ca/intl/en_ca/images/logo.gif">
<script>
$(document).ready( function() {
  $("#mask-div")
    .css({
      "position": "absolute",
      "width": 275,
      "height": 110,
      "background": "rgba(0, 0, 0, 0.5)",
      "display": "block"
    })
    .mouseover( function() {
         $(this).fadeOut("slow");
    })
  ;
  $("#test-img").mouseout( function() {
      $("#mask-div").fadeIn("slow");
  });
});
</script>  
</body>
</html>

非常感谢您的指点

你需要交换一些东西:

  1. 隐藏初始掩码
  2. 图像被鼠标悬停时,显示掩码(当掩码还不可见时,您将鼠标悬停在图像上)
  3. 掩码被鼠标移出时,隐藏掩码(当掩码已经可见时,您将鼠标移出掩码)

: http://jsbin.com/icuvit/3/edit .

  $("#mask-div")
    .css({
      "position": "absolute",
      "width": 275,
      "height": 110,
      "background": "rgba(0, 0, 0, 0.5)"
    })
    .mouseout( function() {
      $("#mask-div").fadeOut("slow");
    })
    .hide();
  $("#test-img")
    .mouseover( function() {
      $("#mask-div").fadeIn("slow");
    });

和一些首次使用的CSS:

#mask-div {
  display: none;
}
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<style>
  article, aside, figure, footer, header, hgroup, 
  menu, nav, section { display: block; }
</style>
</head>
<body>  
  <div id="mask-div"></div>
  <img id="test-img" src="http://www.google.ca/intl/en_ca/images/logo.gif">
<script>
$(document).ready( function() {
  $("#mask-div")
    .css({
      "position": "absolute",
      "width": 275,
      "height": 110,
      "background": "rgba(0, 0, 0, 0.5)",
      "display": "none"
    })
    .mouseout( function() {
         $(this).fadeOut("slow");
    })
  ;
  $("#test-img").mouseover( function() {
      $("#mask-div").fadeIn("slow");
  });
});
</script>  
</body>
</html>

如果您实际使用一些其他选择器导致多个图像,您仍然可以按照以下方式使用pimvdb的技术。

$('.test-img').each(function(){
    var $img = $(this);
    $("#mask-div")
        .css({
        "position": "absolute",
        "width": 275,
        "height": 110,
        "background": "rgba(0, 0, 0, 0.5)"
    })
    .mouseout( function() {
        $("#mask-div").fadeOut("slow");
    })
    .hide();
    $img.mouseover( function() {
        $("#mask-div").fadeIn("slow");
    });
});