參考文檔:jQuery 的擴展,實現抖動效果
背景:在項目中,登錄頁驗證用戶名和密碼是否匹配,如果不匹配,則抖動輸入框,提示用戶輸入錯誤。
將如下代碼寫到JS文件中:
1 jQuery.fn.shake = function (intShakes /*Amount of shakes*/, intDistance /*Shake distance*/, intDuration /*Time duration*/) { 2 this.each(function () { 3 var jqNode = $(this); 4 jqNode.css({ position: 'relative' }); 5 for (var x = 1; x <= intShakes; x++) { 6 jqNode.animate({ left: (intDistance * -1) }, (((intDuration / intShakes) / 4))) 7 .animate({ left: intDistance }, ((intDuration / intShakes) / 2)) 8 .animate({ left: 0 }, (((intDuration / intShakes) / 4))); 9 } 10 }); 11 return this; 12 }
在View中引入以上JS文件以及Jquery文件,代碼如下:
1 <script src="~/Scripts/jquery-1.8.2.js"></script> 2 <script src="~/Scripts/shakeYou.js"></script> 3 <script> 4 $(function () { 5 $('#btn1').click(function () { 6 $(this).shake(2, 10, 400); 7 }); 8 }); 9 </script>
以上代碼的效果是:當點擊btn時,自身抖動。
