神奇简洁的拖动js代码
by joe
at 2009-08-29 11:22:16
original http://xiebiji.com/2009/08/%e7%a5%9e%e5%a5%87%e7%ae%80%e6%b4%81%e7%9a%84%e6%8b%96%e5%8a%a8js%e4%bb%a3%e7%a0%81/
在蓝色论坛发现这个,有点看不懂,研究一下先。
测试地址:code
<!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=gb2312" /> <title>Drag</title> <style> * { font-size:12px; font-family:Verdana,宋体; } html { margin:0px; padding:0px; overflow:auto; } body { margin:0px; padding:15px; background-color:buttonface; } #w { position:absolute; width:480px; height:270px; overflow:hidden; border:2px groove #281; cursor:default; -moz-user-select:none; } #t { line-height:20px; height:20px; width:480px; overflow:hidden; background-color:#27C; color:white; font-weight:bold; border-bottom:1px outset blue; text-align:center; } #winBody { height:248px; width:480px; overflow-x:hidden; overflow-y:auto; border-top:1px inset blue; padding:10px; text-indent:10px; background-color:white; } </style> </head> <body> <div id="w"> <div id="t">Demo Win - Drag me</div> <div id="winBody">Hello world</div> </div> </body> <script> (function(o,s,x,y,d){ s = o.style; d = document; o.onselectstart = function(){ return false; }; //阻止选择 o.onmousedown = function(e){ e = e||event; x = e.clientX-o.offsetLeft; y = e.clientY-o.offsetTop; d.onmousemove = function(e){ e = e||event; s.left = e.clientX - x + "px"; s.top = e.clientY - y + "px"; } d.onmouseup = function(){ d.onmouseup = d.onmousemove = ""; } } })(document.getElementById("w")) </script> </html>
把js代码单独拿出来,认真看一下就会发现原理很简单,用”()”把函数括起来然后在后面直接加”(参数)”运行函数。
(function(o,s,x,y,d){ s = o.style;//id为w的元素直接充当这里的o了 d = document;// o.onselectstart = function(){ return false; }; //阻止选择 o.onmousedown = function(e){ e = e||event; x = e.clientX-o.offsetLeft; y = e.clientY-o.offsetTop; d.onmousemove = function(e){ e = e||event; s.left = e.clientX - x + "px"; s.top = e.clientY - y + "px"; } d.onmouseup = function(){ d.onmouseup = d.onmousemove = ""; } } })(document.getElementById("w"))