如何在按钮点击上使用Jquery Shake效果?

时间:2014-09-19 07:16:32

标签: javascript jquery

我想要做的是在文本框为空时摇动文本框。但我无法做到这一点。 我正在做的如下:

$("#BtnSubmit").click(function() {
              if ($("#txt1").val() == '' || $("#TextBox1").val() == '' || $("#TextBox2").val()) {
                  $("#txt1").effect("shake")

              }

          });

<div id="keepTextBox">
              &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
              &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
              <asp:TextBox ID="txt1" ForeColor="White" runat="server" Height="30px" Style="background-color: #46375E;"></asp:TextBox>&nbsp;&nbsp;
              <asp:RequiredFieldValidator ControlToValidate="txt1" ID="rftxt1" runat="server" SetFocusOnError="true"></asp:RequiredFieldValidator>
              <asp:TextBox ID="TextBox1" ForeColor="White" runat="server" Height="30px" Style="background-color: #46375E"></asp:TextBox>&nbsp;&nbsp;
              <asp:RequiredFieldValidator ControlToValidate="TextBox1" ID="rfTextBox1" runat="server"
                  SetFocusOnError="true"></asp:RequiredFieldValidator>
              <asp:TextBox ID="TextBox2" runat="server" ForeColor="White" Height="30px" Style="background-color: #46375E"></asp:TextBox>&nbsp;&nbsp;
              <asp:RequiredFieldValidator ControlToValidate="TextBox2" ID="rfTextBox2" runat="server"
                  SetFocusOnError="true"></asp:RequiredFieldValidator>
              <asp:Button ID="BtnSubmit" runat="server" Width="15%" Text="SIGN UP" ForeColor="White"
                  Style="background-color: #49A7E4; cursor: pointer;" Height="40px" /></div>
      </div>

1 个答案:

答案 0 :(得分:10)

您必须将jquery UI作为依赖项与jquery一起包含以获取shake effect

$("#txt1").click(function() {
  $(this).effect( "shake" );
});
<button id="txt1">shake it</button>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>

或者

如果您不想包含Jquery UI,则必须按照this answer on SO中的说明实现它。

$("#txt").click(function(){

  $(this).shake();

});
<button id="txt">shake it</button>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
jQuery.fn.shake = function(intShakes, intDistance, intDuration) {
  
    intShakes = intShakes || 10;
    intDistance = intDistance || 2;
    intDuration = intDuration || 1000;
  
    this.each(function() {
        $(this).css("position","relative"); 
        for (var x=1; x<=intShakes; x++) {
        $(this).animate({left:(intDistance*-1)}, (((intDuration/intShakes)/4)))
    .animate({left:intDistance}, ((intDuration/intShakes)/2))
    .animate({left:0}, (((intDuration/intShakes)/4)));
    }
  });
return this;
};
</script>