日期:2014-05-16 浏览次数:20369 次
现在来解决兼容性问题。首先测试IE6,不通过。:(
网上流传的IE不支持事件函数的event参数,改用window.event。
经过测试,我的IE6 sp3是支持event参数的。所以类似代码
var ev = e || window.event
并不需要。
但是IE并不支持从div对象中获取currentTarget,而是支持srcElement。所以下面的代码修改一下:
function mouseDown(e) { 'use strict'; window.dragObj = e.currentTarget || e.srcElement; if (window.dragObj !== null) { window.clickLeft = window.event.x - parseInt(window.dragObj.style.left, 10); window.clickTop = window.event.y - parseInt(window.dragObj.style.top, 10); window.dragObj.style.zIndex += 1; } }
而使用Chrome的时候,上面的e.currentTarget返回的是div对象,div对象我已经在html中设置了style="left:1px...",因此会成功。
Chrome只认div,IE只认img。为了解决这个问题,我在img上同样用上style设置。
html代码修改后:
<html> <head> <title>drag demo</title> <script src="js/drag.js" type="text/javascript"></script> </head> <body onload="init()"> <div id="icon1" onmousedown="mouseDown(event)" style="left:1px; top: 1px; position: absolute;"> <img alt="" border="0" src="/img/2.jpg" style="left:1px; top: 1px; position: absolute;"></img> </div> </body> </html>
/*global window */ function mouseDown(e) { 'use strict'; window.dragObj = e.currentTarget || e.srcElement; if (window.dragObj !== null) { window.clickLeft = window.event.x - parseInt(window.dragObj.style.left, 10); window.clickTop = window.event.y - parseInt(window.dragObj.style.top, 10); window.dragObj.style.zIndex += 1; } } function mouseStop() { 'use strict'; window.event.returnValue = false; } function mouseMove() { 'use strict'; if (window.dragObj !== null) { window.dragObj.style.left = window.event.x - window.clickLeft; window.dragObj.style.top = window.event.y - window.clickTop; } } function mouseUp() { 'use strict'; window.dragObj = null; } function init() { 'use strict'; window.dragObj = null; window.document.onmousemove = mouseMove; window.document.onmouseup = mouseUp; window.document.ondragstart = mouseStop; }