拖拽的原理
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>拖拽的原理</title>
<style type="text/css">
#div1{width: 100px;height: 100px;background: #f00;position:absolute;}
#div2{width: 100px;height: 100px;background: #ff0;position: absolute;left: 400px;top: 200px;}
</style>
</head>
<script>
window.onload=function (){
var oDiv=document.getElementById('div1');
oDiv.onmousedown=function (ev){
var ev=ev||event;
var disX=ev.clientX-oDiv.offsetLeft;
var disY=ev.clientY-oDiv.offsetTop;
document.onmousemove=function (ev){
var ev=ev||event;
oDiv.style.left=ev.clientX - disX + 'px';
oDiv.style.top=ev.clientY - disY + 'px';
}
document.onmouseup=function (){
document.onmousemove=null;
document.onmouseup=null;
}
}
};
</script>
<body>
<div id="div1"></div>
<div id="div2"></div>
</body>
</html>
拖拽的问题及解决办法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>拖拽的问题</title>
<style type="text/css">
#div1{width: 100px;height: 100px;background: #f00;position:absolute;}
</style>
</head>
<script>
window.onload=function (){
var oDiv=document.getElementById('div1');
oDiv.onmousedown=function (ev){
var ev=ev||event;
var disX=ev.clientX-oDiv.offsetLeft;
var disY=ev.clientY-oDiv.offsetTop;
document.onmousemove=function (ev){
var ev=ev||event;
oDiv.style.left=ev.clientX - disX + 'px';
oDiv.style.top=ev.clientY - disY + 'px';
}
document.onmouseup=function (){
document.onmousemove=null;
}
return false;
}
};
</script>
<body>
文字文字文字文字
<div id="div1"></div>
</body>
</html>
全局捕获
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>全局捕获</title>
</head>
<body>
<input type="button" name="" value="按钮一">
<input type="button" name="" value="按钮二">
<script type="text/javascript">
var aInput=document.getElementsByTagName('input');
aInput[0].setCapture();
aInput[0].onclick=function (){
alert(1);
}
aInput[1].onclick=function (){
alert(2);
}
</script>
</body>
</html>
拖拽问题及解决办法2
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>拖拽的问题</title>
<style type="text/css">
#div1{width: 100px;height: 100px;background: #f00;position:absolute;}
</style>
</head>
<script>
window.onload=function (){
var oDiv=document.getElementById('div1');
oDiv.onmousedown=function (ev){
var ev=ev||event;
var disX=ev.clientX-oDiv.offsetLeft;
var disY=ev.clientY-oDiv.offsetTop;
if (oDiv.setCapture){
oDiv.setCapture();
}
document.onmousemove=function (ev){
var ev=ev||event;
oDiv.style.left=ev.clientX - disX + 'px';
oDiv.style.top=ev.clientY - disY + 'px';
if (oDiv.releaseCapture) {
oDiv.releaseCapture();
}
}
document.onmouseup=function (){
document.onmousemove=null;
}
return false;
}
};
</script>
<body>
文字文字文字文字
<div id="div1"></div>
</body>
</html>