在html中,元素可用onclick、ondblclick、onmouseover、onmouseout、onmousedown、onmouseup、onmousemove来对鼠标的各种事件进行响应。本例演示了鼠标对元素的单击、双击、悬停、移走、按下、松开、在元素内的移动来更改元素的背景色。
eg:

<head>
		<meta charset="utf-8">
		<style>
			#container{
				width: 570px;
				height: 200px;
			}
			dl{
				float: left;
			}
			dt{
				width: 90px;
				height: 90px;
				background-color: lightblue;
				border-radius: 20px;
				margin: 10px;
			}
			
			.yellow{
				background-color: lightgoldenrodyellow;
			}
			.blue{
				background-color: lightblue;
			}
		</style>
		<title></title>
	</head>
	<body>
		<div id="container">
			<dl>
				<dt onclick="f1(this)"></dt>
				<dd>单击</dd>
			</dl>
			<dl>
				<dt ondblclick="f2(this)"></dt>
				<dd>双击</dd>
			</dl>
			<dl>
				<dt onmouseover="this.className='yellow'" onmouseout="this.className='blue'"></dt>
				<dd>悬停</dd>
			</dl>
			<dl>
				<dt onmousedown="this.className='yellow'" onmouseup="this.className='blue'"></dt>
				<dd>按下</dd>
			</dl>
			<dl>
				<dt id="ele" onmousemove="mouseMove(event)"></dt>
				<dd>移动</dd>
			</dl>
			<br><span id="echo"></span>
		</div>	
		<script>
			var num1=0,num2=0;
			function f1(e){
				num1++;
				if(num1%2==0)
					e.className="blue";
				else
					e.className="yellow";
			}
			function f2(e){
				num2++;
				if(num2%2==0)
					e.className="blue";
				else
					e.className="yellow";
			}
			function mouseMove(ev){				
				ev=ev||window.event;
				var el=document.getElementById("ele");
				var x=ev.clientX-el.offsetLeft;
				var y=ev.clientY-el.offsetTop;
				if(x<el.offsetWidth/2)
					el.style.background="lightgoldenrodyellow";
				else 
					el.style.background="lightpink";
				document.getElementById("echo").innerHTML="x:"+x+"<br>y:"+y;
			}
		</script>
	</body>

运行结果:
在这里插入图片描述

更多:https://blog.csdn.net/weixin_43873198/article/details/105906484
在线运行源代码:https://gitnlf9527.github.io/Demo/HTML鼠标事件(单击,双击,悬停,按下,移动).html

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐