jQuery 是一个快速、小巧且功能丰富的 JavaScript 库,它简化了 HTML 文档遍历、事件处理、动画和 Ajax 交互。点击收缩和展开多个元素是一种常见的交互效果,通常用于列表项的展开和折叠,以提高用户体验。
以下是一个使用 jQuery 实现点击收缩和展开多个元素的示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery Click Expand and Collapse</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
.item {
border: 1px solid #ccc;
margin-bottom: 10px;
}
.content {
display: none;
}
</style>
</head>
<body>
<div class="item">
<button class="toggle-btn">Toggle</button>
<div class="content">
<p>This is the content of item 1.</p>
</div>
</div>
<div class="item">
<button class="toggle-btn">Toggle</button>
<div class="content">
<p>This is the content of item 2.</p>
</div>
</div>
<script>
$(document).ready(function() {
$('.toggle-btn').click(function() {
$(this).next('.content').slideToggle('fast');
});
});
</script>
</body>
</html>
通过以上方法,可以有效地实现点击收缩和展开多个元素的功能,并解决常见的相关问题。