現在用Firefox最新版本13.0測試,不work,圖片會自動回到原位。
安裝firebug擴充後調試一下。
到console視窗點擊enable後,
錯誤資訊是:
window.event is undefined.
Firefox不支援window.event,因此所有用到event的地方要類似這樣寫:
function mouseDown(e) {'use strict';e = e || window.event;//必須這樣寫window.dragObj = e.currentTarget || e.srcElement;if (window.dragObj !== null) {window.clickLeft = e.x - parseInt(window.dragObj.style.left, 10);window.clickTop = e.y - parseInt(window.dragObj.style.top, 10);window.dragObj.style.zIndex += 1;}}
解決了這個錯誤後,測試一下Chrome和IE6,都工作正常,但是Firefox仍然不行。滑鼠左鍵鬆開的時候,圖片仍然跟著跑。
注意,在Ubuntu12.04+FireFox13.0+FireBug1.9下,debug很容易讓Firefox死掉。
這個問題是因為Firefox的mouseUp事件沒有被觸發。用下面的代碼可以解決,在mouseDown函數中,添加:
if(e.preventDefault) {e.preventDefault();}else {e.returnValue = false;}
這樣mouseUp事件就能正常觸發了。重構一下代碼,再用jslint4java掃描一下,解決了書寫格式後。現在一份同時相容IE6 sp3, Firefox13.0,Chrome的代碼出現了:
/*global window */function getEvent(e) {'use strict';return e || window.event;}function getTarget(e) {'use strict';return e.currentTarget || e.srcElement;}function getPos(e) {'use strict';return {x: e.x || e.clientX,y: e.y || e.clientY};}function mouseDown(e) {'use strict';e = getEvent(e);window.dragObj = getTarget(e);if (e.preventDefault) {e.preventDefault();} else {e.returnValue = false;}if (window.dragObj !== null) {var pos = getPos(e);window.clickLeft = pos.x - parseInt(window.dragObj.style.left, 10);window.clickTop = pos.y - parseInt(window.dragObj.style.top, 10);window.dragObj.style.zIndex += 1;}}/** * IE6.0 need this */function mouseStop(e) {'use strict';e = getEvent(e);e.returnValue = false;}function mouseMove(e) {'use strict';e = getEvent(e);if (window.dragObj !== null) {var pos = getPos(e);window.dragObj.style.left = pos.x - window.clickLeft;window.dragObj.style.top = pos.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;}
做前端真的不容易啊。我還沒有測試IE7,8,9呢!