利用JavaScript实现简单的拖动层(只使用于IE)
本来在项目中不是必须的,但是我觉得如果能实现拖动给客户感觉会更好一点,所以就开始写一个拖动,其实网上有很多可以拿过来就用的源码,但是总想自己写一个,因为我觉得大部分代码写的太多了。所以就参考他们的,写我自己的。
实际上就是用了三个事件函数
1.onmousedown 2.onmousemove 3.onmouseup
利用这三个事件函数就可以了,代码如下:
![](https://www.cnblogs.com/images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/images/OutliningIndicators/ExpandedBlockEnd.gif)
![](https://www.cnblogs.com/images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/images/OutliningIndicators/ExpandedBlockEnd.gif)
![](https://www.cnblogs.com/images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/images/OutliningIndicators/ExpandedBlockEnd.gif)
![](https://www.cnblogs.com/images/OutliningIndicators/None.gif)
html部分是
<div id="div1" style="width: 100px; height: 100px; top:10px; left:15px; cursor:move; background-color:Blue; position:absolute;" onmousedown="mousedown(this)" > </div>
注意事项:
1.要拖动的div一定要把position属性设置absolute;否则按流布局的话无法实现拖动。
2.一定要设置top和left的初始值,否则当onmousemove事件触发时就会报错!
存在问题:
1.只能在IE里用,没有实现跨浏览器。
2.在拖动过程中如果鼠标快速移动,就会移出到被拖动层的外面,这时如果松开鼠标,没有清空onmousemove事件,所以当鼠标指向时就会跟着鼠标移动。
文章来源:http://www.cnblogs.com/interboy/archive/2007/05/02/734642.html
![](https://images.cnblogs.com/cnblogs_com/mephisto/638707/o_%E6%94%AF%E4%BB%98%E5%AE%9D3.png)
![](https://img.alipay.com/sys/personalprod/style/mc/btn-index.png)
博文作者:mephisto
本文版权归作者和博客园共有,欢迎转载,但须保留此段声明,并给出原文链接,谢谢合作!
如果阅读了本文章,觉得有帮助,您可以选择捐助我:
![](http://pic.cnitblog.com/face/22672/20140415170007.png)