onmousedown 是一種滑鼠事件,當滑鼠在元素上按下時觸發。此事件常用於拖拽、選中或其它滑鼠交互。
一、基礎使用
onmousedown 事件的基礎使用非常簡單,只需在 HTML 元素中設置相應的屬性即可:
<div onmousedown="console.log('滑鼠按下了!')"></div>
當滑鼠在該 div 上按下時,控制台將輸出 “滑鼠按下了!” 的信息。
二、常用場景
1. 拖拽
onmousedown 事件通常與 onmousemove 和 onmouseup 事件一起使用,以實現拖拽效果。下面是一個實現拖拽的簡單示例:
<!DOCTYPE html>
<html>
<head>
<style>
#drag { width: 100px; height: 100px; background-color: red; }
</style>
</head>
<body>
<div id="drag" onmousedown="handleMouseDown(event)"></div>
<script>
var isDragging = false;
var dragObj = null;
function handleMouseDown(event) {
isDragging = true;
dragObj = event.target;
}
function handleMouseMove(event) {
if (!isDragging) return;
dragObj.style.left = event.clientX + "px";
dragObj.style.top = event.clientY + "px";
}
function handleMouseUp() {
isDragging = false;
dragObj = null;
}
document.addEventListener("mousemove", handleMouseMove);
document.addEventListener("mouseup", handleMouseUp);
</script>
</body>
</html>
當滑鼠在 #drag 上按下時,拖拽效果就會啟動。在拖拽過程中,handleMouseMove 函數將依據滑鼠的位置更新 #drag 元素的位置,當鬆開滑鼠時,拖拽效果停止。
2. 按鈕交互
onmousedown 事件通常也用於實現按鈕的點擊樣式變化,例如在按鈕按下時給它添加樣式:
<!DOCTYPE html>
<html>
<head>
<style>
.button { padding: 10px 20px; border-radius: 4px; background-color: #42b983; color: white; }
.button:active { background-color: #34a567; }
</style>
</head>
<body>
<button class="button" onmousedown="
this.style.backgroundColor = '#34a567';
this.style.boxShadow = 'inset 0 1px 3px rgba(0,0,0,0.2)';
" onmouseup="
this.style.backgroundColor = '#42b983';
this.style.boxShadow = 'none';
">Click me</button>
</body>
</html>
當按鈕按下時,背景顏色和陰影會發生變化,表現出按鈕已被按下的效果。
三、注意事項
1. 只有滑鼠左鍵觸發
默認情況下,onmousedown 只有在滑鼠左鍵被按下時才會被觸發,如果需要監聽滑鼠的其他鍵,可以使用 event.button 屬性來區分滑鼠鍵位。
<div onmousedown="
if (event.button === 0) console.log('左鍵按下!');
else if (event.button === 1) console.log('中鍵按下!');
else if (event.button === 2) console.log('右鍵按下!');
"></div>
2. IE 低版本的不兼容性
在 IE 低版本中,onmousedown 事件不會在捕獲階段被觸發,只能在冒泡階段中被觸發。因此,當需要取消默認操作時,需要同時設置 return false; 和 event.cancelBubble = true;。
<div onmousedown="
console.log('滑鼠按下了!');
return false;
event.cancelBubble = true;
"></div>
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/235544.html
微信掃一掃
支付寶掃一掃