前端笔记66——鼠标事件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chengxu_kuangrexintu/article/details/86683521

前言

在平时的PC端操作中,我们肯定会发现鼠标双击、鼠标移动等等事件。那么JavaScript关于鼠标事件是怎么样呢?下面就来分享。

鼠标事件

简单理解,和鼠标有关的事件。

事件名称和事件的触发场景

事件名称        	      事件的触发场景

onmousedown           当鼠标按下的时候触发
onmouseup             当鼠标抬起的时候触发
onmouseover   	      当鼠标移入的时候触发
onmouseout            当鼠标移出的时候触发
onclick               当鼠标点击的时候触发
ondblclick            当鼠标双击的时候触发
onmousemove           当鼠标移动的时候触发
oncontextmenu         当鼠标右键的时候触发(可以自定义右键菜单)
鼠标按下抬起事件例子
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style type="text/css">
			#box{
				width: 300px;
				height: 100px;
				background: red;
			}
		</style>
	</head>
	<body>
		<div id="box"></div>
		<script type="text/javascript">
			// 找到div
			var oBox = document.getElementById("box")
			oBox.onmousedown = function(){
				// 改变背景颜色
				oBox.style.backgroundColor = "orange"
			}
			oBox.onmouseup = function(){
				oBox.style.backgroundColor = "red"
			}
		</script>
	</body>
</html>

鼠标的移入和移出事件例子

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style type="text/css">
			a{
				text-decoration: none;
				padding: 20px;
				color: #000000;
			}
		</style>
	</head>
	<body>
		<a href="">学习</a>
		<a href="">工作</a>
		<a href="">游戏</a>
		<a href="">旅游</a>
		<script type="text/javascript">
			var oA = document.getElementsByTagName("a")
			// 批量绑定事件,变量oA这个集合,加事件
			for(var i in oA){
				//当鼠标移入的时候触发
				oA[i].onmouseover = function(){
					// 改变背景颜色,在这里怎样确定移入的是那个
					// this ---> 1 在函数中  2 谁调用这个函数,他就指向
					// this ---> 
					this.style.backgroundColor = "red"
					this.style.color = "white"
				}
				// 当鼠标移动的时候触发
				oA[i].onmouseout = function(){
					this.style.backgroundColor= "white"
					this.style.color = "black"
				}
			}
		</script>
	</body>
</html>

鼠标移动、单击、双击、右键菜单事件例子

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<button>点击</button>
		<script type="text/javascript">
			// 通过标签来查找元素  找到oButton是一个集合
			var oButton = document.getElementsByTagName("button")
			// 事件函数没有执行 1 oButton没有找到 2事件名称写错  3事件函数写错
			oButton[0].ondblclick = function(){
				alert("鼠标双击了")
			}
			// 鼠标的移动事件 document表示整个html文档
			document.onmousemove = function(){
				console.log("鼠标移动了")
			}
			// 右键菜单事件
			document.oncontextmenu = function(){
				alert("右键菜单")
				// 阻止原生(原来)右键菜单
				return false
			}
		</script>
	</body>
</html>

猜你喜欢

转载自blog.csdn.net/chengxu_kuangrexintu/article/details/86683521