1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> <style> *{ margin: 0;padding: 0;list-style: none} #div{ width: 100px;height: 100px;background: pink;position: absolute;} </style> <script> window.onload = function() { var odiv = document.getElementById('div'); var disX = 0; var disY = 0; var scrollTop = document.documentElement.scrollTop || document.body.scrollTop; var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft; odiv.onmousedown = function(event) { disX = event.clientX + scrollLeft - div.offsetLeft; disY = event.clientY + scrollTop - div.offsetTop; document.onmousemove = function(event) { var l = event.clientX - disX; var t = event.clientY - disY; if (l <= 0) { l = 0; } else if (l > document.documentElement.clientWidth - odiv.offsetWidth) { l = document.documentElement.clientWidth - odiv.offsetWidth; } if (t < 0) { t = 0; } else if (t > document.documentElement.clientHeight - odiv.offsetHeight) { t = document.documentElement.clientHeight - odiv.offsetHeight; } odiv.style.left = l + 'px'; odiv.style.top = t + 'px'; } document.onmouseup = function() { document.onmousemove = null; odiv.onmouseup = null; } return false; } } </script> </head> <body> <div id="div"></div> </body> </html>
|