1. 基本用法
首先,让我们来看一个简单的示例,演示如何使用 onmousedown 事件来实现鼠标按下效果。在这个示例中,我们会创建一个按钮,当鼠标按下时,按钮的背景颜色会变成蓝色。
// www.javascriptcn.com code example
<!DOCTYPE html>
<html>
<head>
<title>鼠标按下效果</title>
<style>
.btn {
padding: 10px 20px;
background-color: #f00;
color: #fff;
cursor: pointer;
}
</style>
</head>
<body>
<button class="btn" onmousedown="this.style.backgroundColor = '#00f'">点击我</button>
</body>
</html>在这个示例中,我们给按钮添加了一个 onmousedown 事件,当鼠标按下时,会执行内联的 JavaScript 代码 this.style.backgroundColor = '#00f',将按钮的背景颜色设置为蓝色。
2. 使用事件监听器
除了在 HTML 元素上直接使用 onmousedown 属性外,我们还可以使用事件监听器来监听鼠标按下事件。这种方式更加灵活,可以在 JavaScript 中动态添加和移除事件监听器。
// www.javascriptcn.com code example
<!DOCTYPE html>
<html>
<head>
<title>鼠标按下效果</title>
<style>
.btn {
padding: 10px 20px;
background-color: #f00;
color: #fff;
cursor: pointer;
}
</style>
</head>
<body>
<button class="btn">点击我</button>
<script>
const btn = document.querySelector('.btn');
btn.addEventListener('mousedown', function() {
this.style.backgroundColor = '#00f';
});
</script>
</body>
</html>在这个示例中,我们首先使用 document.querySelector 方法获取按钮元素,然后使用 addEventListener 方法添加鼠标按下事件监听器。当鼠标按下时,会执行回调函数,将按钮的背景颜色设置为蓝色。
3. 阻止默认行为
有时候,我们需要在鼠标按下事件中阻止默认行为,比如在拖拽元素时阻止浏览器的默认拖拽行为。在这种情况下,我们可以在事件处理函数中调用 event.preventDefault() 方法来阻止默认行为。
// www.javascriptcn.com code example
<!DOCTYPE html>
<html>
<head>
<title>拖拽元素</title>
<style>
.box {
width: 100px;
height: 100px;
background-color: #f00;
cursor: move;
}
</style>
</head>
<body>
<div class="box"></div>
<script>
const box = document.querySelector('.box');
box.addEventListener('mousedown', function(event) {
event.preventDefault();
const startX = event.clientX - box.offsetLeft;
const startY = event.clientY - box.offsetTop;
function moveElement(event) {
box.style.left = event.clientX - startX + 'px';
box.style.top = event.clientY - startY + 'px';
}
document.addEventListener('mousemove', moveElement);
document.addEventListener('mouseup', function() {
document.removeEventListener('mousemove', moveElement);
});
});
</script>
</body>
</html>在这个示例中,我们给一个盒子元素添加了鼠标按下事件监听器,当鼠标按下时,会阻止默认行为,并且记录鼠标按下时的坐标。然后在鼠标移动事件中,根据鼠标的位置来移动盒子元素,最后在鼠标松开事件中移除鼠标移动事件监听器,实现了一个简单的拖拽效果。
通过以上示例,我们可以看到使用 onmousedown 事件可以实现一些有趣的效果,同时也可以结合其他事件和方法来实现更加复杂的功能。希望本文对你有所帮助,谢谢阅读!