jQuery 是一个快速、小巧且功能丰富的 JavaScript 库,它简化了 HTML 文档遍历、事件处理、动画和 Ajax 交互。显示和隐藏事件是 jQuery 中常用的功能之一,主要用于控制页面元素的可见性。
.show()
方法可以显示隐藏的元素。.hide()
方法可以隐藏显示的元素。.toggle()
方法可以在显示和隐藏之间切换。<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery Show/Hide Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
#box {
width: 100px;
height: 100px;
background-color: red;
display: none;
}
</style>
</head>
<body>
<button id="toggleButton">Toggle Box</button>
<div id="box"></div>
<script>
$(document).ready(function() {
$('#toggleButton').click(function() {
$('#box').toggle();
});
});
</script>
</body>
</html>
$(document).ready()
函数中,确保 DOM 元素加载完成后再绑定事件。通过以上方法,可以有效地解决 jQuery 显示和隐藏事件中遇到的常见问题。
领取专属 10元无门槛券
手把手带您无忧上云