我是jQuery的新手。目前,我正在使用跨平台移动应用程序中的jQuery。我需要在各自的条件下隐藏和显示我的一些页面内容。我发现以下两种方法对我来说很好。
$( "#myControlId" ).fadeOut();
$( "#myControlId" ).hide();
这两条线对我来说都很好,可以隐藏我的观点,当我需要显示我的观点后,两条线对我来说都很好
$( "#myControlId" ).fadeIn();
$( "#myControlId" ).show();
只是想知道它们之间的技术差异,当我需要使用哪个功能来满足特定需求时。
.fadeIn(duration)
和.fadeOut(duration)
动画显示持续时间中不透明度的百分比。在褪色动画期间,元素的位置被完全占据,但是在.fadeOut()
的末尾,该位置将立即被移除。.show(duration)
和.hide(duration)
将元素的大小(也是不透明度)设置为100%和0%,元素的位置也会在该持续时间内生成动画。.hide()
和.fadeOut()
中消失,并且当持续时间= 0时立即出现在.show()
和.fadeIn()
中。运行此代码段以检查差异和相似之处:
$(document).ready(function(){
$("#fadeOut1000").click(function(){
$("#rectangle").stop().fadeOut(1000);
})
$("#fadeOut0").click(function(){
$("#rectangle").stop().fadeOut(0);
})
$("#hide1000").click(function(){
$("#rectangle").stop().hide(1000);
})
$("#hide0").click(function(){
$("#rectangle").stop().hide(0);
})
$("#fadeIn1000").click(function(){
$("#rectangle").stop().fadeIn(1000);
})
$("#fadeIn0").click(function(){
$("#rectangle").stop().fadeIn(0);
})
$("#show1000").click(function(){
$("#rectangle").stop().show(1000);
})
$("#show0").click(function(){
$("#rectangle").stop().show(0);
})
})
#placeholder{
width:300px;
height:100px;
border:1px solid #666666;
margin:auto;
margin-top:10px;
}
#rectangle{
width:300px;
height:100px;
background:#ff0000;
}
a{
display:inline-block;
margin:5px;
border-radius:5px;
border:1px solid #aaaaaa;
padding:5px;
cursor:pointer;
width:90px;
font-size:9pt;
font-family:tahoma;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="text-align:center">
<a id="fadeOut1000">fadeOut(1000)</a>
<a id="fadeOut0">fadeOut(0)</a>
<a id="hide1000">hide(1000)</a>
<a id="hide0">hide(0)</a>
<br>
<a id="fadeIn1000">fadeIn(1000)</a>
<a id="fadeIn0">fadeIn(0)</a>
<a id="show1000">show(1000)</a>
<a id="show0">show(0)</a>
<div id="placeholder">
<div id="rectangle"></div>
</div>
</div>
show(),fadeIn()和hide(),fadeOut()的工作方式相似。
下表显示了它们之间基于css属性的区别。
| Opacity | Display | Width/Height |
对于show(),hide()
|Changes |Changes |Changes |
对于fadeIn(),fadeOut()
|Changes |Changes |Doesn't change|
这是一个演示代码,您可以检查以便更好地理解:
HTML
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>JQuery</title>
<script src="../scripts/jquery-3.2.1.min.js"></script>
<script src="../scripts/myscript.js"></script>
</head>
<body>
<p>Hey</p>
<button>Click me!</button>
<p></p>
<div id="div1" style="width:80px;height:80px;display:none;background-color:red;"></div><br>
<div id="div2" style="width:80px;height:80px;display:none;background-color:blue;"></div>
</body>
</html>
脚本(myscript.js)
$(document).ready(function () {
$('button').click(function () {
$("#div1").show(10000);
$("#div2").fadeIn(10000);
});
});
可以添加到此操作差异的一个重点是hide()/ show()保存了初始显示值。如果你的元素有一个显示:在显示之前的内联:由于hide()而没有,那么它应该再次内联。
它在the doc :)
匹配的元素将立即隐藏,没有动画。这大致相当于调用.css(“display”,“none”),除了将display属性的值保存在jQuery的数据高速缓存中,以便稍后可以将显示恢复到其初始值。如果元素的显示值为内联并且隐藏然后显示,则它将再次以内联方式显示。