JavaScript

超轻量级php框架startmvc

JS实现的简单拖拽功能示例

更新时间:2020-04-29 12:06:01 作者:startmvc
本文实例讲述了JS实现的简单拖拽功能。分享给大家供大家参考,具体如下:1、实例代码:

本文实例讲述了JS实现的简单拖拽功能。分享给大家供大家参考,具体如下:

1、实例代码:


<!DOCTYPE html>
<html>
 <head>
 <meta charset="utf-8" />
 <title>js实现拖拽</title>
 <style>
 #water{
 width:400px;
 height:188px;
 background-color: #ff6600;
 }
 #water:hover{
 cursor: pointer;
 }
 </style>
 </head>
 <body>
 <div id="water"></div>
 <script>
 dragInit("water");//调用
 //拖拽初始化
 function dragInit(id){
 var $div = document.getElementById(id);
 var style = {
 position: "absolute",
 left: "0",
 top: "0"
 }
 for(var k in style){
 $div.style[k] = style[k];//设置关键css
 }
 $div.onmousedown = function(e){//鼠标按键按下
 e = e || window.event;
 var x = e.clientX - $div.offsetLeft;//鼠标到左上角的距离信息, 固定不变
 var y = e.clientY - $div.offsetTop;
 document.onmousemove = function(e){//鼠标移动
 e = e || window.event;
 var L = e.clientX - x;
 var T = e.clientY - y;
 var pW = document.documentElement.clientWidth;//页面宽度
 var pH = document.documentElement.clientHeight;
 var divW = $div.offsetWidth;//Dom宽度
 var divH = $div.offsetHeight;
 // 范围限定
 if(L < 0){
 L = 0;
 }
 if(T < 0){
 T = 0;
 }
 if(L > pW - divW){
 L = pW - divW;
 }
 if(T > pH - divH){
 T = pH - divH;
 }
 // 范围限定 end
 $div.style.left = L + "px";
 $div.style.top = T + "px";
 };
 document.onmouseup = function(e){//鼠标按键松开
 document.onmousemove = null;
 };
 };
 }
 </script>
 </body>
</html>

2、运行效果图如下:

JS 拖拽