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>