这个布局蛮简单的就是一个div块,通过定位,固定位置
1 <html> 2 3 <head> 4 <meta charset="UTF-8"> 5 <title></title> 6 <style type="text/css"> 7 #div { 8 width: 200px; 9 height: 200px; 10 background: pink; 11 position: absolute; 12 top: 0; 13 left: 0; 14 cursor: pointer; 15 } 16 </style> 17 </head> 18 19 <body> 20 <div id="div"> 21 22 </div> 23 <div id="div2"></div> 24 </body> 25 26 </html>
在js代码中需要用到onmousedown和onmouseup这一对方法来实现
而o=event||ev;event表示一般浏览器,而ev则表示ie浏览器,所以o就可以在不同的浏览器中同样实现相同效果
1 <script type="text/javascript"> 2 var Div = document.getElementById("div"); 3 Div.onmousedown = function(ev) { 4 var o = event || ev; 5 //获取到鼠标点击的位置距离div左侧和顶部边框的距离 6 oX = o.clientX - parseInt(getStyle(Div, "left")); 7 oY = o.clientY - parseInt(getStyle(Div, "top")); 8 //当鼠标移动,把鼠标的偏移量给div 9 document.onmousemove = function(ev) { 10 var o = event || ev; 11 //计算出鼠标在XY方向上移动的偏移量,把这个偏移量加给DIV的左边距和上边距,div就会跟着移动 12 Div.style.left = o.clientX - oX + "px"; 13 Div.style.top = o.clientY - oY + "px"; 14 } 15 16 //当鼠标按键抬起,清除移动事件 17 document.onmouseup = function() { 18 document.onmousedown = null; 19 document.onmousemove = null; 20 } 21 } 22 23 24 //获取属性的数值 25 function getStyle(obj, attr) { 26 if (obj.currentStyle) { 27 //currentStyle获取样式的值,对应的是ie浏览器 28 return obj.currentStyle[attr]; 29 } else { 30 //同理,对应的是其他浏览器 31 return getComputedStyle(obj, false)[attr]; 32 } 33 } 34 </script>