掌握 jQuery 基礎語法:引入庫、DOM 就緒、選擇器、事件綁定、動畫方法。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>jQuery 顯示/隱藏/切換 Demo</title>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>
<style>
#text {
padding: 20px;
background: #e8f4fd;
border: 1px solid #3498db;
border-radius: 4px;
margin-bottom: 10px;
/* display: none; 默認隱藏可取消註釋 */
}
button {
padding: 8px 16px;
margin-right: 8px;
cursor: pointer;
border: 1px solid #ccc;
background: #fff;
border-radius: 3px;
}
button:hover { background: #f0f0f0; }
</style>
</head>
<body>
<p id="text">這是一段被折騰的文本 — 可以隱藏、顯示、切換</p>
<button id="btnHide">隱藏</button>
<button id="btnShow">顯示</button>
<button id="btnToggle">切換 (隱藏/顯示)</button>
<script>
// 核心:文檔就緒後綁定事件
$(document).ready(function() {
// 隱藏按鈕
$('#btnHide').click(function() {
$('#text').hide(); // 瞬間隱藏
// $('#text').fadeOut(400); // 淡出動畫 400ms
});
// 顯示按鈕
$('#btnShow').click(function() {
$('#text').show(); // 瞬間顯示
// $('#text').fadeIn(400); // 淡入動畫
});
// 切換按鈕
$('#btnToggle').click(function() {
$('#text').toggle(); // 瞬間切換
// $('#text').fadeToggle(400); // 淡入淡出切換
});
});
</script>
</body>
</html>
| 方法 | 作用 | 動畫版本 | 參數 |
|---|---|---|---|
.hide() | 設置 display:none 隱藏元素 | .fadeOut(duration) | duration: 'fast'/'slow'/毫秒數 |
.show() | 恢復 display 顯示元素 | .fadeIn(duration) | 同上 |
.toggle() | 切換顯示/隱藏狀態 | .fadeToggle(duration) | 同上 |
.slideUp() | 向上滑動隱藏 | 內建動畫 | duration |
.slideDown() | 向下滑動顯示 | 內建動畫 | duration |
.slideToggle() | 滑動切換 | 內建動畫 | duration |
$(function(){...})#id (ID)、.class (類)、tag (標籤)、[attr=value] (屬性)$('#text').fadeOut(400).delay(200).fadeIn(400)$('.item').hide() 自動遍歷所有匹配元素,無需手動循環.animate()$('#text').click(function() {
$(this).animate({
opacity: 0.5,
fontSize: '20px',
marginLeft: '50px'
}, 800, 'swing', function() {
console.log('動畫完成回調');
});
});
.stop(true, true) 清空隊列並跳到終態$('#text').stop(true, true).fadeToggle(400);fadeIn 前需確保元素在文檔流中 (可用 visibility:hidden 替代).load() .unload() 等別名,用 .on() 統一綁定