2011-01-20 88 views
62

我想知道如何禁用右鍵單擊圖像使用jQuery。禁用使用jquery右鍵單擊圖像

我只知道這一點:

<script type="text/javascript" language="javascript"> 
    $(document).ready(function() { 
     $(document).bind("contextmenu",function(e) { 
      return false; 
     }); 
    }); 
</script> 
+3

這應該有時工作;)。但忘記吧,還有其他100種從網絡上保存圖像的方式。順便說一下,如果你傳遞了點擊的對象,然後使用它! http://jsfiddle.net/VZX4A/ – meo 2011-01-20 23:11:25

+3

是的,我知道。我這樣做只是爲了降低圖像副本的數量。它專門用於那些只知道右鍵點擊並保存愚蠢用戶的人。 – 2011-01-20 23:33:07

+3

只是不。您無法保護圖像不被複制,並且禁用瀏覽器的默認和預期功能。 – 2011-01-20 23:48:17

回答

133

這工作:

$('img').bind('contextmenu', function(e) { 
    return false; 
}); 

或者較新的jQuery:

$('#nearestStaticContainer').on('contextmenu', 'img', function(e){ 
    return false; 
}); 

jsFiddle example

10

什麼是你禁止的目的右鍵點擊。任何技術的問題在於總有一種方法可以繞過它們。 firefox(firebug)和chrome的控制檯允許解除該事件的綁定。或者如果你想讓圖像受到保護,人們總是可以看看圖像的臨時緩存。

如果你想創建自己的上下文菜單中的preventDefault是罰款。在這裏挑選你的戰鬥吧。甚至沒有像tnyMCE這樣的大型JavaScript庫可以在所有瀏覽器上工作......並不是因爲這是不可能的;-)。

$(document).bind("contextmenu",function(e){ 
    e.preventDefault() 
}); 

我個人更喜歡開放的互聯網。原生瀏覽器行爲不應受到頁面交互的阻礙。我相信可以找到其他方式進行交互,這不是正確的點擊。

7

對於禁用右鍵點擊選項

<script type="text/javascript"> 
    var message="Function Disabled!"; 

    function clickIE4(){ 
     if (event.button==2){ 
      alert(message); 
      return false; 
     } 
    } 

    function clickNS4(e){ 
     if (document.layers||document.getElementById&&!document.all){ 
      if (e.which==2||e.which==3){ 
       alert(message); 
       return false; 
      } 
     } 
    } 

    if (document.layers){ 
     document.captureEvents(Event.MOUSEDOWN); 
     document.onmousedown=clickNS4; 
    } 
    else if (document.all&&!document.getElementById){ 
     document.onmousedown=clickIE4; 
    } 

    document.oncontextmenu=new Function("alert(message);return false") 
</script> 
2

有沒有可能離開右擊並在完成後單獨水印被放置在圖像上剛剛下載的能力。當然,這不會阻止屏幕截圖,但認爲這可能是一個好的中間立場。

7

在Chrome和Firefox上述方法沒有工作,除非我用的不是「綁定」「活」。

這爲我工作:

$('img').live('contextmenu', function(e){ 
    return false; 
}); 
1

你可以試試這個:

var message="Sorry, right-click has been disabled"; 

function clickIE() { 
    if (document.all) { 
     (message); 
     return false; 
    } 
} 

function clickNS(e) { 
    if (document.layers || (document.getElementById && !document.all)) { 
     if (e.which == 2||e.which == 3) { 
      (message); 
      return false; 
     } 
    } 
} 

if (document.layers) { 
    document.captureEvents(Event.MOUSEDOWN); 
    document.onmousedown = clickNS; 
} else { 
    document.onmouseup = clickNS; 
    document.oncontextmenu = clickIE; 
} 

document.oncontextmenu = new Function("return false") 

Checkout a demo here

1

一個非常簡單的方法是將圖像添加爲背景,以一個DIV,然後負載一個空的透明gif設置爲與前景中的DIV相同的大小。這使得不那麼確定。他們無法獲取背景,而無法查看代碼並複製URL並右鍵單擊下載透明gif。