DIV CSS 佈局教程網

JavaScript 實現簡單滑鼠拖動效果(含邊界限制)
編輯:關於JavaScript     

本文分享如何實作滑鼠拖動效果,讓元素能被拖到網頁任意位置,例如許多部落格模板都允許使用者自行拖動版塊位置。

基本原理:滑鼠按下時記錄滑鼠位置與元素左側距離的差值;滑鼠移動時,用滑鼠位置減去該差值作為元素的新位置;滑鼠放開時,把移動與放開事件設為 null,停止後續動作。

要點一:

 disx = oevent.clientX - box.offsetLeft;

確認拖動時滑鼠点在元素上的位置,即滑鼠位置減去元素左側距離。

要點二:

 box.style.left = oevent.clientX - disx + "px";

拖動時元素的新位置等於滑鼠當前位置減去剛才算出的差值。

程式碼如下:

 <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>無標題文檔</title> <style> body{margin:0; padding:0; height:1500px;} #box{width:100px; height:100px; background:#06c; position:absolute;} </style> <script> window.onload = function(){ var box = document.getElementById("box"); var disx =0; var disy = 0; box.onmousedown = function(evt){ var oevent = evt || window.event; disx = oevent.clientX - box.offsetLeft; disy = oevent.clientY - box.offsetTop; document.onmousemove = function(evt){ var oevent = evt || window.event; box.style.left = oevent.clientX - disx + "px"; box.style.top = oevent.clientY - disy + "px"; } document.onmouseup = function(){ document.onmousemove = null; document.onmouseup = null; } return false; } } </script> </head> <body> <h1>滑鼠拖動</h1> <div id="box"></div> </body> </html>

再進一步優化:上面的拖動沒有邊界限制,元素可能被拖到視窗外而看不見。下面加上範圍限制——當元素左側位置小於 0 時設為 0,大於「可視窗寬度減去元素寬度」時設為該差值;上下同理。

 var boxl = oevent.clientX - disx; if(boxl < 0){ boxl =0; }else if(boxl > vieww - box.offsetWidth){ boxl = vieww - box.offsetWidth; } <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>無標題文檔</title> <style> body{margin:0; padding:0;} #box{width:100px; height:100px; background:#06c; position:absolute; } </style> <script> window.onload = function(){ var box = document.getElementById("box"); var disx =0; var disy = 0; box.onmousedown = function(evt){ var oevent = evt || window.event; disx = oevent.clientX - box.offsetLeft; disy = oevent.clientY - box.offsetTop; document.onmousemove = function(evt){ var oevent = evt || window.event; var boxl = oevent.clientX - disx; var boxt = oevent.clientY - disy var vieww = document.documentElement.clientWidth || document.body.clientWidth; var viewh = document.documentElement.clientHeight || document.body.clientHeight; if(boxl < 0){ boxl =0; }else if(boxl > vieww - box.offsetWidth){ boxl = vieww - box.offsetWidth; } if(boxt < 0){ boxt =0; }else if(boxt > viewh - box.offsetHeight){ boxt = viewh- box.offsetHeight; } box.style.left = boxl + "px"; box.style.top = boxt + "px"; } document.onmouseup = function(){ document.onmousemove = null; document.onmouseup = null; } return false; } } </script> </head> <body> <h1>滑鼠拖動</h1> <div id="box"></div> </body> </html>

希望本文所述對大家的 JavaScript 程式設計有所幫助。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved