<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<style>
*{ margin:0; top:0}
#box{ height:200px; width:200px; background:red; position:absolute; cursor:move}
</style>
<script>
window.οnlοad=function(){
var oDiv=document.getElementById('box');
var oInput=document.getElementsByTagName('input')[0];
//阻止内部标签的事件冒泡;使oInput标签在onmousedown下会聚焦,能输入文本。
oInput.οnmοusedοwn=function(ev){
ev=ev||window.event; //IE8以下事件对象是window.event
ev.cancelBubble=true;
};
oDiv.οnmοusedοwn=function(ev){
ev=ev||window.event;
//计算偏移距离
var disX=ev.clientX-oDiv.offsetLeft; //distance 距离
var disY=ev.clientY-oDiv.offsetTop;
//开始拖动------------------------------------------
document.οnmοusemοve=function(ev){
ev=ev||window.event;
var l=ev.clientX-disX; //鼠标x
var t=ev.clientY-disY;//鼠标y
console.log(l,t);
//先判断,后赋值
if(l<0){
l=0;
};
if(t<0){
t=0;
};
var screenW=document.documentElement.clientWidth; //浏览器窗口宽度
var screenH=document.documentElement.clientHeight; //浏览器窗口高度
if(l>screenW-oDiv.offsetWidth){
l=screenW-oDiv.offsetWidth;
};
if(t>screenH-oDiv.offsetHeight){
t=screenH-oDiv.offsetHeight;
};
oDiv.style.left=l+"px";
oDiv.style.top=t+"px";
};
//停止拖动 动作写在document上-----------------------------
document.οnmοuseup=function(){
document.οnmοusemοve=null;
};
//阻止默认事件,这里指的具体默认事件是 “鼠标会选中oDiv里面的内容” 这一事件
return false;
};
};
</script>
</head>
<body>
<div id="box">dsf sdf sadf sadf sadf adsf sad fas df safd ad fa fd asd asdf
<input type="text" value="3234243234">
</div>
</body>
</html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<style>
*{ margin:0; top:0}
#box{ height:200px; width:200px; background:red; position:absolute; cursor:move}
</style>
<script>
window.οnlοad=function(){
var oDiv=document.getElementById('box');
var oInput=document.getElementsByTagName('input')[0];
//阻止内部标签的事件冒泡;使oInput标签在onmousedown下会聚焦,能输入文本。
oInput.οnmοusedοwn=function(ev){
ev=ev||window.event; //IE8以下事件对象是window.event
ev.cancelBubble=true;
};
oDiv.οnmοusedοwn=function(ev){
ev=ev||window.event;
//计算偏移距离
var disX=ev.clientX-oDiv.offsetLeft; //distance 距离
var disY=ev.clientY-oDiv.offsetTop;
//开始拖动------------------------------------------
document.οnmοusemοve=function(ev){
ev=ev||window.event;
var l=ev.clientX-disX; //鼠标x
var t=ev.clientY-disY;//鼠标y
console.log(l,t);
//先判断,后赋值
if(l<0){
l=0;
};
if(t<0){
t=0;
};
var screenW=document.documentElement.clientWidth; //浏览器窗口宽度
var screenH=document.documentElement.clientHeight; //浏览器窗口高度
if(l>screenW-oDiv.offsetWidth){
l=screenW-oDiv.offsetWidth;
};
if(t>screenH-oDiv.offsetHeight){
t=screenH-oDiv.offsetHeight;
};
oDiv.style.left=l+"px";
oDiv.style.top=t+"px";
};
//停止拖动 动作写在document上-----------------------------
document.οnmοuseup=function(){
document.οnmοusemοve=null;
};
//阻止默认事件,这里指的具体默认事件是 “鼠标会选中oDiv里面的内容” 这一事件
return false;
};
};
</script>
</head>
<body>
<div id="box">dsf sdf sadf sadf sadf adsf sad fas df safd ad fa fd asd asdf
<input type="text" value="3234243234">
</div>
</body>
</html>