JS实现拖拽的虚线框
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
#div1 {
width: 100px;
height: 100px;
background: red;
position: absolute;
}
.box {
border: 1px dashed black;
position: absolute;
}
</style>
<script>
window.onload = function() {
var oDiv = document.getElementById('div1');
var disX = 0;
var disY = 0;
oDiv.onmousedown = function(ev) {
var oEvent = ev || event;
disX = oEvent.clientX - oDiv.offsetLeft;
disY = oEvent.clientY - oDiv.offsetTop;
//虚线框
var oBox = document.createElement('div');
oBox.className = 'box';
//设置box的宽高
oBox.style.width = oDiv.offsetWidth - 2 + 'px';
oBox.style.height = oDiv.offsetHeight - 2 + 'px';
//设置出现的位置
oBox.style.left = oDiv.offsetLeft + 'px';
oBox.style.top = oDiv.offsetTop + 'px';
document.body.appendChild(oBox);
function mouseMove(ev) {
var oEvent = ev || event;
var l = oEvent.clientX - disX;
var t = oEvent.clientY - disY;
//这里移动的是box
oBox.style.left = l + 'px';
oBox.style.top = t + 'px';
};
function mouseUp() {
//将box的位置给div
oDiv.style.left = oBox.offsetLeft + 'px';
oDiv.style.top = oBox.offsetTop + 'px';
//移除box
document.body.removeChild(oBox);
this.onmousemove = null;
this.onmouseup = null;
if(this.releaseCapture) {
this.releaseCapture();
}
}
//兼容性判定
if(oDiv.setCapture) {
//IE
oDiv.onmousemove = mouseMove;
oDiv.onmouseup = mouseUp;
oDiv.setCapture();
} else {
//Chrome/FF
document.onmousemove = mouseMove;
document.onmouseup = mouseUp;
}
return false; //chrome,ff,ie9
}
}
</script>
</head>
<body>
<div id="div1"></div>
</body>
</html>
JS添加事件兼容的一个简单小函数
function myAddEvent(obj,ev,fn)
{
if(obj.attachEvent)
{
obj.attachEvent('on'+ev,fn);
}else
{
obj.addEventListener(ev,fn,false);
}
}
window.onload=function(){
var oDiv = document.getElementById('btn1');
myAddEvent(oDiv,'click',function(){
alert('abc');
})
myAddEvent(oDiv,'click',function(){
alert('ced');
})
}