2015-09-25 62 views
1

我有一個允許用戶鍵入簡短(50個字符)的註釋的彈出框。我需要做的是弄清楚如何防止用戶使用鼠標右鍵單擊複製/粘貼筆記。在asp.net上捕獲鼠標文本框

我擡起頭來看所有的​​爲一個文本框,onkeyup和onkeydown不在此列表中,但它們確實有效果。

我有以下的JavaScript捕捉按鍵:

<!--//********************************** 
    // Comment Character Count 
    //********************************** --> 
<script type="text/javascript"> 
    function textCounter(field, countfield, maxlimit) { 
    if (field.value.length > maxlimit) 
     field.value = field.value.substring(0, maxlimit); 
    else 
     countfield.value = maxlimit - field.value.length; 
    } 
</script> 

,然後將此文本框這就要求當一個鍵被按下上面的功能:

<asp:TextBox ID="txtCommentBox" TextMode="MultiLine" CssClass="textbox" Wrap="True" 
Height="70px" Width="270px" Font-Size="Small" Rows="3" runat="server" 
onkeyup="textCounter(this, this.form.remLen, 50);" 
onkeydown="textCounter(this, this.form.remLen, 50);" /> 

一切工作真棒,除了當一個人的權利點擊並選擇「粘貼」,它會繞過檢查,因爲沒有按鍵。任何想法如何陷阱?有沒有無證的onmouseclick事件我可以打電話或什麼?

+0

IIRC,我認爲可能會有'onpaste'事件。此外,一個'onchange'事件可能會有用。我只是從記憶中工作,所以我可能會誤會... –

+0

請參閱:http://stackoverflow.com/questions/737022/how-do-i-disable-right-click-on-my-web-頁面 –

回答

1

首先,onpaste事件添加到您的文本框:

<asp:TextBox ID="txtCommentBox" TextMode="MultiLine" CssClass="textbox" Wrap="True" 
Height="70px" Width="270px" Font-Size="Small" Rows="3" runat="server" 
onkeyup="textCounter(this, this.form.remLen, 50);" 
onkeydown="textCounter(this, this.form.remLen, 50);" 
onpaste="textCounter(this, this.form.remLen, 50);" /> 

接下來,適應Fabrício Matté's解決方案來處理onpaste射擊和value之間的時間差被填充:

function textCounter(field, countfield, maxlimit) { 
    setTimeout(function() { 
     if (field.value.length > maxlimit) 
      field.value = field.value.substring(0, maxlimit); 
     else 
      countfield.value = maxlimit - field.value.length; 

    }, 0); 
} 
+0

完美適用於所有潛在的使用和濫用。謝謝! –

1

使用TextBox.MaxLength財產。即使粘貼文本,它也會阻止添加其他字符。您還可以添加asp.net自定義驗證器,以確保用戶在瀏覽器編輯器中沒有更改您的html。

<asp:TextBox ID="txtCommentBox" TextMode="MultiLine" CssClass="textbox" Wrap="True" 
Height="70px" Width="270px" Font-Size="Small" Rows="3" runat="server" MaxLength="50"/>