我的 HTML 代码是:
<!DOCTYPE html>
<html>
<head>
<title>Furry Friends Campaign</title>
<link rel="stylesheet" type="text/css" href="styles/my_style.css">
</head>
<body>
<div id="clickMe">Show me the the Furry Friend of the Day</div>
<div id="picframe">
<img src="images/furry_friend.jpg" alt="Our Furry Friend">
</div>
<script type="text/javascript" src="scripts/jquery-3.1.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$("#clickMe").click(function()
{
$("img").fadeIn(1000);
$("#picframe").slideToggle("slow");
});
});
</script>
</body>
</html>
附带的 CSS 如下所示:
#clickMe {
background: #D8B36E;
padding: 20px;
text-align: center;
width: 205px;
display: block;
border: 2px solid #000;
}
#picframe {
background: #D8B36E;
padding: 20px;
width: 205px;
display: none;
border: 2px solid #000;
}
slideToggle 工作得很好,但由于某种原因,图像没有淡入。我尝试将持续时间设置为更长的时间,但结果相同。有人可以指出这段代码有什么问题吗?我使用的是最新版本的 Chrome。
更新:我尝试运行我正在使用的书中的示例代码,它使用 jquery-1.6.2.min.js
并使用该版本的 jQuery,该代码完美运行。这是 jQuery 的一些错误吗?或者是现在做事的新方式?
最佳答案
自 jQuery 1.8 起,fadeIn 最初不再隐藏图像,因此尝试淡入可见或未将 display
设置为 none
的图像不会'不会导致任何结果。
要淡入,你应该先隐藏它。最初它没有隐藏,因为子级不继承 display
CSS 属性,并且您仅在父级 #picframe
上将其设置为 none
的图像。只需添加 $("img").hide();
即可。这将使它起作用。
因为看起来您需要在每次点击时淡入/淡出,您可以执行以下操作而不是 $("img").fadeIn(1000)
:
if($("img").is(":hidden")) $("img").fadeIn(1000);
else $("img").fadeOut(1000);
下面的演示。
#clickMe {
background: #D8B36E;
padding: 20px;
text-align: center;
width: 205px;
display: block;
border: 2px solid #000;
}
#picframe {
background: #D8B36E;
padding: 20px;
width: 205px;
display: none;
border: 2px solid #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<div id="clickMe">Show me the the Furry Friend of the Day</div>
<div id="picframe">
<img src="images/furry_friend.jpg" alt="Our Furry Friend">
</div>
<script type="text/javascript" src="scripts/jquery-3.1.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
//$("img").hide();
$("#clickMe").click(function() {
$("img").fadeIn(1000);
$("#picframe").slideToggle("slow");
});
});
</script>
关于javascript - 为什么 fadeIn() 不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38686308/