本文分享JS實現簡單div拖拽功能的方法,供有需要的朋友參考。具體實現如下:
<!DOCTYPE HTML>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>拖拽div</title>
<style type="text/css">div{ position:absolute; width:150px; height:150px; background-color:#C8FFFF; }</style>
<script type="text/javascript">
<!--
function drag(obj) {
if (typeof obj == "string") { var obj = document.getElementById(obj); obj.orig_index=obj.style.zIndex; }
obj.onmousedown=function (a){
this.style.cursor="move";
this.style.zIndex=1000;
var d=document;
if(!a) a=window.event;
var x=a.clientX-document.body.scrollLeft-obj.offsetLeft;
var y=a.clientY-document.body.scrollTop-obj.offsetTop;
d.onmousemove=function(a){
if(!a) a=window.event;
obj.style.left=a.clientX+document.body.scrollLeft-x;
obj.style.top=a.clientY+document.body.scrollTop-y;
};
d.onmouseup=function (){
document.onmousemove=null; document.onmouseup = null; obj.style.cursor="normal"; obj.style.zIndex=obj.orig_index;
};
}\br /> }
//-->
</script>
</head>
<body>
<div id="div1"></div>
<div id="div2" style="left:170px; background-color:#408080"></div>
<script type="text/javascript">
<!-- drag("div1"); drag("div2"); -->
</script>
</body>
</html>
希望本文所述對大家的JavaScript程序設計有所幫助。