JavaScript鼠标移动事件及案例

一、鼠标点击事件

1.onclick单击事件

        鼠标单击时事件处理函数

<input type="button" id="bt" value="点击">
<script>
//找到按钮并设置点击事件
   document.getElementById("bt").onclick  = function (){
        //被点击后弹出弹出框
       alert("按钮被点击")
   }

</script>

2.ondblclick双击事件

 鼠标双击时事件处理函数

<input type="button" id="bt" value="点击">
<script>
//找到按钮并设置双击击事件
   document.getElementById("bt").ondblclick  = function (){
        //被点击两次后弹出弹出框
       alert("按钮被点击")
   }
 
 </script

 

3. onmousedown鼠标按下事件

        当鼠标被按下后事件处理函数

4. onmouseup鼠标松开事件

        当鼠标被松开后事件处理函数

案例:

 

二、鼠标移动事件

1.onmouseover移入事件
          鼠标移动都某个指点的HTML标签上时触发的事件

2.onmouseout移出事件
           鼠标从HTML标签上移开时触发的事件

3.onmousemove移动事件
          鼠标指针在该元素的上面移动就触发

4.mouseenter移入事件
         于onmouseover相同但mouseenter事件只执行一次

5.mouseleave移出事件
         于onmouseout相同但mouseenter事件只执行一次

 

二、案列:

效果图如下:

 

完整代码如下:

<html>
	<head>
		<meta charset="utf-8">
		<title>鼠标跟随</title>
		<style type="text/css">
			div{
				position: relative;
				width: 360px;
				height: 511px;
			}
			img{
				width: 360px;
				border-radius: 5px;/* 设置圆角 */
			}
			p{
				width: 100px;
				height: 30px;
				position: absolute;/* 绝对定位 */
				left: 0;
				top: 0;
				background-color: rgba(0,0,0,0.666);
				color: white;
				padding: 10px;
				display: none;/* 隐藏 */
				pointer-events: none;/* 不对鼠标事件作出反应 */
			}
		</style>
	</head>
	<body>
		<div id="div_1">
			<img src="img/1.jpg" alt="">
			<p>
				<strong>简介</strong>
				<span>买建材上京东!京东</span>
			</p>
		</div>
		<script type="text/javascript">
			//获取div标签
			var div_1 = document.getElementById("div_1");
			//给div_1绑定事件:onmouseover:鼠标移入事件
			div_1.onmouseover = function(){
				//将p标签显示出来,故需要将display的值设置为block
				document.querySelector("p").style.display = "block";
			}
			//onmouseout:鼠标从元素上移开时触发的事件
			div_1.onmouseout = function(){
				将p标签显示出来,故需要将display的值设置为none
				document.querySelector("p").style.display = "none";
			}
			//onmousemove:鼠标从元素上移动时触发的事件
			div_1.onmousemove = function(){
				document.querySelector("p").style.left =event.offsetX + "px";
				document.querySelector("p").style.top =event.offsetY + "px";
			}
		</script>
	</body>
</html>

  • 3
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱吃汉堡的代码人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值