現在來解決相容性問題。首先測試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;}}
還有一個問題,當IE的時候,上面的e.srcElement返回的是div裡面的img對象,因此再取img對象的style.left屬性的時候會失敗。
而使用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>
JavaScript完整代碼修改後如下:
/*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;}
現在IE6也支援了。