js 拖拽
Posted Sunshine
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了js 拖拽相关的知识,希望对你有一定的参考价值。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <div style="width: 100px;height: 100px;position: absolute;top: 0;left: 0;background-color: #00008B;"> </div> <script type="text/javascript"> var div = document.getElementsByTagName(‘div‘)[0]; drap(div); function drap(elem) { var disX, disY; addEvent(elem, ‘mousedown‘, function(e) { var event = e || window.event; disX = event.pageX - parseInt(getStyle(elem, ‘left‘)); disY = event.pageY - parseInt(getStyle(elem, ‘top‘)); addEvent(document, ‘mousemove‘, mouseMove); addEvent(document, ‘mouseup‘, mouseUp); stopBubble(event); cancelHandler(event); }); function mouseMove(e) { var event = e || window.event; elem.style.left = event.pageX - disX + ‘px‘; elem.style.top = event.pageY - disY + ‘px‘; } function mouseUp(e) { var event = e || window.event; removeEvent(document, ‘mousemove‘, mouseMove); removeEvent(document, ‘mouseup‘, mouseUp); } } function addEvent(elem, type, handle) { if (elem.addEventListener) { elem.addEventListener(type, handle, false); } else if (elem.attachEvent) { elem.attachEvent(‘on‘ + type, function() { handle.call(elem); }) } else { elem[‘on‘ + type] = handle; } } //获取样式 function getStyle(elem, prop) { if (window.getComputedStyle) { return window.getComputedStyle(elem, null)[prop]; } else { return elem.currentStyle[prop]; } } function stopBubble(event) { if (event.stopPropagation) { event.stopPropagation(); } else { event.stopBubble = true; } } function cancelHandler(event) { if (event.preventDefault) { event.preventDefault(); } else { event.returnValue = false; } } function removeEvent(elem, type, myFunction) { if (elem.removeEventListener) { // // 所有浏览器,除了 IE 8 及更早IE版本 elem.removeEventListener(type, myFunction); } else if (elem.detachEvent) { // IE 8 及更早IE版本 elem.detachEvent(‘on‘ + type, myFunction); } } </script> </body> </html>
以上是关于js 拖拽的主要内容,如果未能解决你的问题,请参考以下文章