JavaScript拖拽圖片四

來源:互聯網
上載者:User

現在用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呢!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.