2009-12-11 53 views
3

什麼是跨瀏覽器方法?我需要防止對圖像執行任何默認操作,以便拖動或其他任何操作都不會在默認的基礎上觸發。我們如何防止JavaScript中的默認操作?

+0

請說明你的問題 – Pierreten 2009-12-11 07:03:13

+0

一切都很清楚。仔細讀。 – 2009-12-11 07:19:13

+4

艾倫安德森,如果有人要求你澄清你的問題,你可能會認爲,你看起來很清楚的東西並不一定對其他人清楚。你的問題是非常不清楚的。 – eyelidlessness 2009-12-11 08:10:56

回答

1

您只能取消特定事件。您不能「全局取消」默認操作。

爲了具體取消dragging的圖像(其僅是缺省功能在某些瀏覽器),則返回falsemousedown事件。

+2

您可以全局取消很多默認操作,但不是全部。在這種情況下(原諒糟糕的代碼)'document.onmousedown = function(e){if(typeof e =='undefined')e = window.event; if(e.preventDefault)e.preventDefault();如果(e.stopPagagation)e.stopPropagation(); e.returnValue = false;返回false; };但顯然這會產生很多令人討厭的副作用。 – eyelidlessness 2009-12-11 07:09:02

+0

的確如此,這會產生令人討厭的副作用,但肯定更多的是全球概念。 – 2009-12-11 07:10:55

+0

補充:適用於幾乎任何氣泡的事件。對於「事件授權」(顯然這是一個重疊的概念,並不完全是1:1)和非冒泡事件已經取得了一些進展,但我不知道這些事件是如何實現的。我知道jQuery最近的alpha已經開始實現這些,所以它可能值得一看。 – eyelidlessness 2009-12-11 07:14:01

5

您可以註冊要取消的活動,然後從其中註冊return false或使用Event.preventDefault(),具體取決於瀏覽器和事件。

+0

這不適用於跨瀏覽器。但是海報並未指定哪些瀏覽器是針對的。 – squiddle 2009-12-11 10:28:49

4
(function() { 
    var onmousedown; 
    if('onmousedown' in document && typeof document.onmousedown == 'function') { 
     onmousedown = document.onmousedown; 
    } 
    document.onmousedown = function(e) { 
     if(typeof e == 'undefined') { 
      e = window.event; 
     } 
     if(!e.target) { 
      e.target = e.srcElement || document; 
     } 
     if('nodeName' in e.target && e.target.nodeName.toLowerCase() == 'img') { 
      if(e.preventDefault) { 
       e.preventDefault(); 
      } 

      // If you want to register mousedown events for 
      // elements containing images, you will want to 
      // remove the next four lines. 
      if(e.stopPropagation) { 
       e.stopPropagation(); 
      } 
      e.cancelBubble = true; 

      e.returnValue = false; 
      return false; 
     } 

     if(onmousedown !== undefined) { 
      onmousedown(e); 
     } 
    }; 
})(); 

你可能需要做一些類似你想阻止其他事件的東西,如果你想要的東西,這並不這樣做。

另外值得注意的是,如果您試圖阻止人們將圖片從網頁下載到他們的計算機上,您將無法獲得成功。如果瀏覽器可以下載圖像,用戶也可以下載。使用JavaScript來阻止(一些)嘗試很容易通過簡單地禁用JavaScript來繞過。