<input type="button" value="把滑鼠移上來"
onmouseover="this.style.color='red'"
onmouseout="this.style.color='blue'">
onmouseover:滑鼠進入元素觸發。onmouseout:滑鼠離開元素觸發。this.style.color:直接操作行內樣式,優先級最高。<style>
.btn-hover {
color: blue;
transition: color 0.2s ease; /* 平滑過渡 */
}
.btn-hover:hover {
color: red;
}
</style>
<input type="button" class="btn-hover" value="把滑鼠移上來">
優勢:
:active、鍵盤聚焦 :focus 等狀態。const btn = document.querySelector('.btn-hover');
btn.addEventListener('mouseenter', () => btn.classList.add('highlight'));
btn.addEventListener('mouseleave', () => btn.classList.remove('highlight'));
// CSS
.highlight { color: red; font-weight: bold; }
mouseenter/mouseleave 避免事件冒泡導致的閃爍(區別於 mouseover/mouseout)。classList 而非 style,保持樣式集中管理。tabindex="0" 或原生 <button>)。:focus-visible 樣式,鍵盤用戶同樣獲得視覺回饋。