HOWTO · jQuery
jQuery 中的 is(:visible)
本教程演示如何在 jQuery 中使用 is(:visible)。
:visible 选择器用于检查 HTML 文档中的元素是否可见,is() 是 jQuery 的内置方法。本教程演示如何在 jQuery 中使用 .is(":visible") 选择器。
在 jQuery 中使用 .is(":visible") 选择器
有时,需要检查页面中的元素是否可见;为此,使用了来自 jquery 的内置选择器 .is(":visible")。语法包含一个方法 is() 和一个选择器:visible。
该方法和选择器一起检查元素是否在页面上可见。此方法的语法是:
$(element).is(":visible");
其中 :visible 是一个 CSS 选择器,它告诉用户选择页面上可见的元素。此方法的返回值是元素是否可见。
is() 方法来自 jQuery,用于根据传递给它的选择器检查特定的元素集,并且它不会创建一个新对象来检查相同的对象而不进行任何修改。
让我们尝试一个简单的示例,如果给定元素可见或不可见,它将提醒我们:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery is visible method </title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js""> </script>
<style>
#delftstack {
display: block;
}
</style>
<script>
$(document).ready(function() {
// Check whether the delftstack h1 is visible
if($("h1").is(":visible")) {
alert("The h1 element with delftstack is visible.");
}
else {
alert("The h1 element with delftstack is not visible.");
}
});
</script>
</head>
<body>
<h1 id = "delftstack">Hello, This is delftstack.com</h1>
</body>
</html>
h1 的显示设置为 block,因此该元素在文档中可见。查看输出:
同样,如果显示设置为 none,则该元素将在文档中不可见。参见示例:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery is visible method </title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js""> </script>
<style>
#delftstack {
display: none;
}
</style>
<script>
$(document).ready(function() {
// Check whether the delftstack h1 is visible
if($("h1").is(":visible")) {
alert("The h1 element with delftstack is visible.");
}
else {
alert("The h1 element with delftstack is not visible.");
}
});
</script>
</head>
<body>
<h1 id = "delftstack">Hello, This is delftstack.com</h1>
</body>
</html>
此代码的输出是:
我们还可以使用 .is(":visible") 方法来隐藏和显示元素。让我们尝试一个例子:
<!DOCTYPE html>
<html>
<head>
<title>
is visible jQuery
</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
</head>
<body style="text-align:center;">
<h1 style = "color:blue;" > DELFTSTACK </h1>
<h3>
Is Visible JQuery
</h3>
<p style="display: none;">
Delftstack.com - The Best Tutorial Site
</p>
<input onclick="change()" type="button" value="Display" id="DemoButton"> </input>
<script type="text/javascript">
$(document).ready(function() {
$("#DemoButton").click(function() {
if (this.value == "Display")
this.value = "Hide";
else this.value = "Display";
$("p").toggle("slow", function() {
if($("p").is(":visible")) {
alert("The P element is visible.");
}
else {
alert("The p element is hidden.");
}
});
});
});
</script>
</body>
</html>
上面的代码将在点击时显示或隐藏段落元素,使用 .is(":visible") 方法进行检查。见输出: