<html>
<head>
<title>简单的DIV拖动</title>
<script type="text/javascript">
function mydrag(id, id_title, id_content) {
var obj = document.getElementById(id);
var obj_title = document.getElementById(id_title);
var obj_content = document.getElementById(id_content);
var beginx, beginy, endx, endy;
var isdown = false;
function mousedown(ev)
{
var event = window.event || ev; //ie与其他浏览器的兼容性
beginx = event.clientX;
beginy = event.clientY;
isdown = true;
obj.style.opacity=0.7; //实现半透明效果
}
function mousemove(ev)
{
if(isdown){
var event = window.event || ev;
endx = event.clientX;
endy = event.clientY;
obj.style.left = parseInt(obj.style.left)+endx-beginx; //obj.style.left带有单位px
obj.style.top = parseInt(obj.style.top)+endy-beginy;
beginx = endx; //更新坐标
beginy = endy;
setSelected(obj_content, false);
}
}
function mouseup()
{
isdown = false;
obj.style.opacity=1.0;
setSelected(obj_content, true);
}
function setSelected(target, boo){
//设置文字是否可以复制boo=true时可以复制,否则禁止复制
if (typeof target.onselectstart!="undefined"){ //IE
target.onselectstart=function(){
return boo;
}
}else if (typeof target.style.MozUserSelect!="undefined"){ //Firefox
/*MozUserSelect有三个值:
*1.none表示所有子元素都不能被选择
*2.-moz-all子元素的所有文字都可以被选择
*3.-moz-none子元素的所有文字都不能选择,但input除外
*/
if(boo) target.style.MozUserSelect="-moz-all";
else target.style.MozUserSelect="none";
}else{ //other
target.οnmοusedοwn=function(){
return boo;
}
}
}
obj_title.onmousedown = mousedown;
obj_title.onmousemove = mousemove;
obj_title.onmouseup = mouseup;
setSelected(obj_title, false);
setSelected(obj_content,true);
}
window.οnlοad=function(){
mydrag("nav", "title");
}
</script>
<style type="text/css">
#nav{
width: 800px;
height: 100px;
border:1px solid #92B0DD;
background-color: #FFFFFf;
position:absolute; <!--position默认为静态的,所以这里必须声明为相对的或绝对的,否则无法移动-->
}
#title{
background:#EEFAFF;
padding:10px;
}
</style>
</head>
<body>
<div id="nav" style="left:300px;top:200px;">
<!--必须设置left,top的初始值,parseInt(obj.style.left||top)为空-->
<div id="title" style="cursor:move;">我是标题</div>
<div id="content">我是内容</title>
</div>
</body>
</html>
div弹出框拖拽
最新推荐文章于 2024-07-17 09:19:35 发布