事件的冒泡,默认行为,拖拽

 阻止事件冒泡和默认行为

事件冒泡:从里往外逐个触发,在触发事件的时候会一层一层的向上冒泡(他同时会影响父类的事件)

阻止事件冒泡:就是阻止事件向上传递

 btn.onclick = function(e){
            e = e ||window.event        //获取事件源
            if( e.stopPropagation){        //兼容写法
                e.stopPropagation()
            }else{
                e.cancellBubble = true
            }
            console.log('小盒子点击');
        }

 事件阻止默认行为

 <a href="http://www.baidu.com">a链接</a>
    <script>
        document.getElementsByTagName('a')[0].onclick = function(e){
            console.log('点击');
            // return flase 
            // e.preventDefault
            // e.returnValue = flase
            //兼容写法
            e.preventDefault?e.preventDefault:(e.returnValue = flase)
        }
    </script>

鼠标的拖拽:鼠标按下去,然后移动就会跟着动,鼠标松开就不动了

 <style>
        #box{
        width: 100px;
        height: 100px;
        background-color: red;
        position: absolute;
    }
    </style>
</head>
<body>
    <div id="box"></div>
    <script>
        var box = document.getElementById('box')
        //鼠标按下
        box.onmousedown = function(){
            //鼠标移动 
            box.onmousemove = function(e){
                e = e ||window.event
                //获取鼠标的偏移
                var x = e.pageX
                var y = e.pageY
                //获取盒子的中心
                var w = box.offsetWidth/2
                var h = box.offsetHeight/2
                //设置left值和top的值
                var left = x - w
                var top = y -h
                //这个盒子的偏移位置是
                this.style.left = left + 'px'
                this.style.top = top + 'px'
            }
           
        }
        //鼠标弹起
        box.onmouseup = function(){
                box.onmousemove = function(){
                    
                }
            }

    </script>

注意:

onmousedown触发事件的对象: 目标元素(即要拖拽的元素);

onmousemove触发事件的对象: document

onmouseup触发事件的对象: document

onmousemove和onmouseup的触发事件对象都是document, 意味着鼠标在网页的任意位置移动鼠标或松开鼠标,都会触发对应的事件;

onmousemove和onmouseup 都要写在onmousedown事件中, 这样就可以保证鼠标按下后才可以移动目标元素(onmousemove)或停止移动(onmouseup)

获取style样式

if (window.getComputedStyle) {

    style = window.getComputedStyle(box, null);    //支持IE9+及非IE浏览器

} else {

    style = box.currentStyle// IE8及以前

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值