JavaScript中onmouseover,onmouseout和onmouseenter,onmouseleave的区别

JavaScript中onmouseover,onmouseout和onmouseenter,onmouseleave的区别

onmouseover,onmouseout和onmouseenter,onmouseleave这两组都是鼠标的移入与移出的事件

它们的主要区别在于onmouseenter,onmouseleave这一组默认没有冒泡
事件冒泡:当子元素的某个事件被触发时,会依次向上触发所有父元素的相同事件,这种现象叫事件冒泡
下面先拿onmouseover和onmouseenter来进行比较

	<!--html部分-->
    <div class="box1">
        <div class="box2">
            <div class="box3"></div>
        </div>
    </div>
/*css部分*/
.box1{width: 300px;height: 300px;background: orangered;}
.box2{width: 200px;height: 200px;background: pink;}
.box3{width: 100px;height: 100px;background: royalblue;}

基本效果图

//js部分
	var obox1 = document.querySelector("#box1")
    var obox2 = document.querySelector("#box2")
    var obox3 = document.querySelector("#box3")

    obox1.onmouseover = function(eve){
        var e = eve || window.event;
		console.log("橙色div")
    }
    obox2.onmouseover = function(eve){
        var e = eve || window.event;		
		console.log("粉色div")
    }
    obox3.onmouseover = function(eve){
        var e = eve || window.event;		
        console.log("蓝色div")
    }
    document.onmouseover = function(){
        console.log("document")
    } 

当我们将鼠标移入最里面的蓝色div时,在控制台中将会依次打印蓝色div、粉色div、橙色div、document,这种现象就是冒泡
但是当我们把onmouseover换为onmouseenter时

	obox1.onmouseenter = function(eve){
       var e = eve || window.event;
		console.log("橙色div")
    }
    obox2.onmouseenter = function(eve){
        var e = eve || window.event;		
		console.log("粉色div")
    }
    obox3.onmouseenter = function(eve){
        var e = eve || window.event;		
        console.log("蓝色div")
    }
    document.onmouseenter = function(){
        console.log("document")
    } 

当我们将鼠标移入最里面的蓝色div时,在控制台中只打印了蓝色div.
以上就是onmouseenter和onmouseout的主要区别,onmouseout和onmouseleave也同理。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值