標籤:
拖拽效果
HTML
<!DOCTYPE html><html> <head> <meta charset="utf-8"> <title>拖拽效果</title> <link rel="stylesheet" type="text/css" href="拖拽效果.css"> </head> <body> <div id="box"> <h1 id="heading">點擊拖拽</h1> </div> <script src="拖拽效果.js"></script> </body></html>
CSS
#box { width:300px; height:300px; background-color:red; padding:10px; border:5px solid green; text-align: center; position:absolute; top:50px; left:50px;}#heading { background-color: blue;}
JavaScript
//頁面載入完畢之後調用drag函數window.onload = drag;//封裝drag函數function drag() { //擷取heading元素 var heading = document.getElementById("heading"); //滑鼠在heading元素地區按下時執行fnDown函數 heading.onmousedown = fnDown; //滑鼠在頁面中鬆開時取消拖拽效果 document.onmouseup = function() { document.onmousemove = null; };};//封裝fnDown函數function fnDown(event) { event = event || window.event; var box = document.getElementById("box"), heading = document.getElementById("heading"), //取得滑鼠點擊的那個點與box左上方的距離 disY = event.clientY - box.offsetTop, disX = event.clientX - box.offsetLeft; //滑鼠在頁面中移動時執行匿名函數 document.onmousemove = function(event) { event = event || window.event; //核心思想是:滑鼠在哪兒,box跟到哪兒 //計算box距離頁面左上方的距離 var t = event.clientY - disY, l = event.clientX - disX, window_width = document.documentElement.clientWidth || document.body.clientWidth, window_height = document.documentElement.clientHeight || document.body.clientHeight, max_t = window_height - box.offsetHeight, max_l = window_width - box.offsetWidth; //控制box移動的最大最小距離 if(t < 0) { t = 0; } else if(t > max_t) { t = max_t; }; if(l < 0) { l = 0; } else if(l > max_l) { l = max_l; }; //box的位置跟隨滑鼠游標 box.style.top = t + "px"; box.style.left = l + "px"; };};
JS 滑鼠事件練習—拖拽效果