阻止事件冒泡和默认行为
事件冒泡:从里往外逐个触发,在触发事件的时候会一层一层的向上冒泡(他同时会影响父类的事件)
阻止事件冒泡:就是阻止事件向上传递
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及以前
}