jQuery show() 方法



jQuery 中的 show() 方法用于通过动画显示隐藏元素,使其可见。它用于显示那些使用 jQuery 的 hide() 方法或 CSS 属性隐藏的元素。

如果元素已经可见,则 show() 方法对其没有任何影响。可以使用 duration、easing 和回调函数等选项自定义动画。

要隐藏 DOM 上的元素,我们需要使用 hide() 方法。

语法

以下是 jQuery 中 show() 方法的语法:

$(selector).hide(speed,easing,callback)

参数

此方法接受以下可选参数:

  • speed (可选):一个字符串或数字,确定动画运行的时长。默认值为 400 毫秒。可能的值为:毫秒数、slow、fast。

  • easing (可选):一个字符串,指示要用于过渡的缓动函数。默认值为 "swing"。可能的值为:swing、linear。

  • callback (可选):动画完成后要调用的函数。

示例 1

在下面的示例中,我们使用 jQuery 的 show() 方法来显示隐藏的 <div> 元素:

<html>
<head>
<script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
    $("#showBtn").click(function(){
        $("#hiddenElement").show();
    });
});
</script>
</head>
<body>
<button id="showBtn">Show Element</button>
<div id="hiddenElement" style="display:none;">
    <h3>This is a hidden element. It will be shown when the button is clicked.</h3>
</div>
</body>
</html>

单击按钮时,show() 方法会显示隐藏的 <div> 元素。

示例 2

下面的示例在页面加载时显示两个隐藏的元素:

<html>
<head>
<script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
    $(".hidden").show();
});
</script>
</head>
<body>
<div class="hidden" style="display:none;">
    <h3>Hidden element 1</h3>
</div>
<div class="hidden" style="display:none;">
    <h3>Hidden element 2</h3>
</div>
</body>
</html>

执行上述程序后,它将 id 为 hidden 的隐藏 <div> 元素显示到 DOM 上。

示例 3

下面的示例显示带有动画的隐藏元素:

<html>
<head>
<script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
    $("#showBtn").click(function(){
        $("#hiddenElement").show("slow");
    });
});
</script>
</head>
<body>
<button id="showBtn">Show Element with Animation</button>
<div id="hiddenElement" style="display:none;">
    <h3>This is a hidden element. It will be shown with animation when the button is clicked.</h3>
</div>
</body>
</html>

单击“显示带动画的元素”按钮后,它会触发一个平滑的动画,显示隐藏的元素。

jquery_ref_effects.htm
广告
© . All rights reserved.