在asp.net文本框上捕获鼠标点击

时间:2015-09-25 18:25:42

标签: javascript c# asp.net textbox

我有一个弹出框,允许用户输入简短的(50个字符)音符。我需要做的是弄清楚如何使用鼠标右键单击来防止用户复制/粘贴笔记。

我查找了所有events available的文本框,而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);" />

一切都很棒,除非有人右击并选择&#34;粘贴&#34;,它会绕过检查,因为没有按下任何键。关于如何陷阱的任何想法?是否有我可以打电话或其他事情的无证件onmouseclick事件?

2 个答案:

答案 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"/>

答案 1 :(得分:1)

首先,在TextBox中添加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);
}
相关问题