事件绑定
<script>
window.onload = function () {
var oDiv = document.getElementById('btn')
if (oDiv.attachEvent) { //低版本的 ie
oDiv.attachEvent('onclick', function () {
alert(a)
})
oDiv.attachEvent('onclick', function () {
alert(a)
})
}else{ // 谷歌和火狐
oDiv.addEventListener('click', function(){
alert('a')
}, false)
oDiv.addEventListener('click', function(){
alert('b')
}, false)
}
}
</script>
封装成函数
<script>
window.onload = function () {
var oDiv = document.getElementById('btn')
myAddEvent(oDiv, 'click', function(){
alert(9)
})
myAddEvent(oDiv, 'click', function(){
alert(8)
})
}
function myAddEvent(obj, ev, fn){
if(obj.attachEvent){
obj.attachEvent('on' + ev, fn)
}else{
obj.addEventListener(ev, fn, false)
}
}
</script>
解除绑定:detachEvent、removeEventListener
磁性吸附
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#div1 {width: 100px; height: 100px; background-color: red; border: 1px solid #999; position: absolute;}
#div2{width: 800px; height: 500px; position: relative; background: #ccc;}
</style>
</head>
<body>
<div id="div2">
<div id="div1"></div>
</div>
<script>
window.onload = function () {
var oDiv = document.getElementById('div1')
var oDiv2 = document.getElementById('div2')
oDiv.onmousedown = function (ev) {
var oEvent = ev || event
var disX = 0
var disY = 0
disX = oEvent.clientX - oDiv.offsetLeft
disY = oEvent.clientY - oDiv.offsetTop
document.onmousemove = function (ev) {
var oEvent = ev || event
var l = oEvent.clientX - disX
var t = oEvent.clientY - disY
if(l < 80){ //当小于80 就等于0
l = 0
}else if(l > oDiv2.offsetWidth - oDiv.offsetWidth - 80){
l = oDiv2.offsetWidth - oDiv.offsetWidth
}
if(t < 80){
t = 0
}else if(t > oDiv2.offsetHeight - oDiv.offsetHeight - 80){
t = oDiv2.offsetHeight - oDiv.offsetHeight
}
oDiv.style.left = l + 'px'
oDiv.style.top = t + 'px'
}
document.onmouseup = function () {
document.onmousemove = null
document.onmouseup = null
}
}
}
</script>
</body>
拖拽选中文字解决方案
<script>
window.onload = function () {
var oDiv = document.getElementById('div1')
oDiv.onmousedown = function (ev) {
var oEvent = ev || event
var disX = 0
var disY = 0
disX = oEvent.clientX - oDiv.offsetLeft
disY = oEvent.clientY - oDiv.offsetTop
oDiv.onmousemove = function (ev) {
var oEvent = ev || event
var l = oEvent.clientX - disX
var t = oEvent.clientY - disY
oDiv.style.left = l + 'px'
oDiv.style.top = t + 'px'
}
oDiv.onmouseup = function () {
document.onmousemove = null
document.onmouseup = null
oDiv.releaseCapture() //去除事件捕获
}
oDiv.setCapture() //事件捕获,将所有元素的事件放到 oDiv 上
//setPointerCapture
//return false //可以解决谷歌、火狐和高版本ie的问题
}
}
</script>