<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>無標題文檔</title> <style> #div1 {width: 100px; height: 100px; background: red; position: absolute;} #img1 { position: absolute;} </style> <script> window.onload = function() { var oDiv = document.getElementById('div1'); var oImg = document.getElementById('img1'); drag(oImg); drag(oDiv); function drag(obj) { obj.onmousedown = function(ev) { var ev = ev || event; var disX = ev.clientX - this.offsetLeft; var disY = ev.clientY - this.offsetTop; if ( obj.setCapture ) { obj.setCapture(); } document.onmousemove = function(ev) { var ev = ev || event; var L = ev.clientX - disX; //拖動元素左側的位置=當前鼠標距離瀏覽器左側的距離 - (物體寬度的一半) var T = ev.clientY - disY; //拖動元素頂部的位置=當前鼠標距離瀏覽器頂部的距離 - (物體高度的一半) if ( L < 0 ) { //如果左側的距離小於0,就讓距離等於0.不能超出屏幕左側。如果需要磁性吸附,把0改為100或者想要的數字即可 L = 0; } else if ( L > document.documentElement.clientWidth - obj.offsetWidth ) { //如果左側的距離>屏幕的寬度-元素的寬度。也就是說元素的右側超出屏幕的右側,就讓元素的右側在屏幕的右側上 L = document.documentElement.clientWidth - obj.offsetWidth; } if ( T < 0 ) { //和左右距離同理 T = 0; } else if ( T > document.documentElement.clientHeight - obj.offsetHeight ) { T = document.documentElement.clientHeight - obj.offsetHeight; } obj.style.left = L + 'px'; obj.style.top = T + 'px'; } document.onmouseup = function() { document.onmousemove = document.onmouseup = null; if ( obj.releaseCapture ) { obj.releaseCapture(); } } return false; } } } </script> </head> <body> <div id="div1"></div> <img src="1.jpg" id="img1" /> </body> </html>
