純 HTML/CSS 無法實現「點擊標籤切換文字顯隱」與「滑鼠懸停暫停跑馬燈」等互動行為,必須引入 JavaScript(或 jQuery 等庫)處理事件邏輯。
<div class="profile-field">
<span class="label" data-target="intro-content">個人簡介</span>
<div id="intro-content" class="content hidden">這是隱藏的詳細內容...</div>
</div>
.hidden { display: none; }
.visible { display: block; }
.label { cursor: pointer; color: #0066cc; text-decoration: underline; }
document.querySelectorAll('.label').forEach(label => {
label.addEventListener('click', function() {
const targetId = this.dataset.target;
const content = document.getElementById(targetId);
if (content) {
content.classList.toggle('hidden');
content.classList.toggle('visible');
// 可選:切換標籤文字
this.textContent = content.classList.contains('hidden') ? '展開' : '收起';
}
});
});
$('.label').on('click', function() {
$('#' + $(this).data('target')).slideToggle(200);
});
<marquee> 或 CSS 動畫)<marquee> 標籤(簡單但非標準)<marquee id="marquee" behavior="scroll" direction="left" onmouseover="this.stop()" onmouseout="this.start()">
這是滾動的公告內容...
</marquee>
onmouseover 呼叫 stop(),onmouseout 呼叫 start() 為標準屬性。
<div class="marquee-container">
<div class="marquee-content">這是用 CSS 動畫實現的跑馬燈內容</div>
</div>
.marquee-container {
overflow: hidden;
white-space: nowrap;
}
.marquee-content {
display: inline-block;
padding-left: 100%;
animation: marquee 10s linear infinite;
}
.marquee-content:hover {
animation-play-state: paused; /* 關鍵:CSS 原生暫停 */
}
@keyframes marquee {
0% { transform: translateX(0); }
100% { transform: translateX(-100%); }
}
無需 JavaScript 即可實現懸停暫停!animation-play-state: paused 是關鍵。
const marquee = document.querySelector('.marquee-content');
let animationId, position = 0, speed = 1;
function animate() {
position -= speed;
if (position <= -marquee.offsetWidth) position = marquee.parentElement.offsetWidth;
marquee.style.transform = `translateX(${position}px)`;
animationId = requestAnimationFrame(animate);
}
marquee.parentElement.addEventListener('mouseenter', () => cancelAnimationFrame(animationId));
marquee.parentElement.addEventListener('mouseleave', animate);
animate(); // 啟動
<!-- Vue 3 Composition API -->
<script setup>
import { ref } from 'vue';
const showContent = ref(false);
const toggle = () => showContent.value = !showContent.value;
</script>
<template>
<div class="field">
<span class="label" @click="toggle">{{ showContent ? '收起' : '展開' }}簡介</span>
<div v-show="showContent" class="content">詳細內容...</div>
</div>
</template>
button 而非 span 作為觸發元素,天生支援鍵盤焦點與 Screen Reader。aria-expanded="true/false"、aria-controls="target-id" 標示狀態與關聯。prefers-reduced-motion 媒體查詢停用選項。| 需求 | 推薦技術 | 關鍵點 |
|---|---|---|
| 點擊切換顯隱 | JS 事件監聽 + CSS class 切換 | data-* 屬性綁定目標、classList.toggle |
| 跑馬燈懸停暫停 | CSS Animation + :hover { animation-play-state: paused } | 零 JS、效能最佳、標準相容 |
| 複雜互動邏輯 | Vue/React 狀態管理 | 資料驅動視圖、組件複用 |
現代前端開發核心:**HTML 定語意、CSS 定呈現與動畫、JS 定邏輯與狀態**。善用 CSS 原生能力(如 animation-play-state、:hover、:focus-within)能大幅減少 JavaScript 程式碼,提升效能與維護性。