<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> * { margin: 0; padding: 0; } html, body { height: 100%; overflow: hidden; } #box { position: absolute; width: 150px; height: 150px; background-color: orangered; } </style> </head> <body> 略略略 <div id="box"></div> <script> window.onload = function () { var box = document.getElementById("box"); box.onmousedown = function (e) { e = e || window.event; var mouseDownPoint = { "x": 0, "y": 0 }; var boxStartPoint = { "x": 0, "y": 0 }; boxStartPoint.x = this.offsetLeft; boxStartPoint.y = this.offsetTop; mouseDownPoint.x = e.clientX; mouseDownPoint.y = e.clientY; // 使用全局捕获,阻止ie8以下浏览器事件的默认行为 if (this.setCapture) { this.setCapture(); } document.onmousemove = function (e) { e = e || window.event; var mouseMovePoint = { "x": 0, "y": 0 }; mouseMovePoint.x = e.clientX; mouseMovePoint.y = e.clientY; box.style.left = mouseMovePoint.x - mouseDownPoint.x + boxStartPoint.x + "px"; box.style.top = mouseMovePoint.y - mouseDownPoint.y + boxStartPoint.y + "px"; return false; // 无法禁止ie8以下浏览器事件的默认行为 } document.onmouseup = function () { document.onmousemove = document.onmouseup = null; if (document.releaseCapture) { // 取消全局捕获 document.releaseCapture(); } } } } </script> </body> </html>
兼容ie8,使用全局捕获,阻止ie8以下浏览器事件的默认行为