大家对于表单验证一定不会陌生。
当没有通过验证的时候通过会出现各种类型的提示效果。
本章节分享一段更为新颖的提示方式,当提交失败的时候,会出现抖动效果。
代码实例如下:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>jQuery实现表单登录失败左右晃动代码示例-搞代码gaodaima.com</title> <style type="text/css"> body{font:12px Georgia, serif;} a{text-decoration:none;} #box{ width:400px; height:200px; background-color:#ccc; text-align:center } </style> <script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script> <script type="text/javascript"> var box_left=0; $(document).ready(function(){ box_left = ($(window).width()-$('#box').width()) / 2; $('#box').css({ 'left':box_left, 'position':'absolute' }); $("a").click(function(){ shock(); return false; }) }); function shock(){ for(i=1;i<7;i++){ $('#box').animate({ 'left':'-=15' }, 3, function() { $(this).animate({ 'left': '+=30' }, 3, function() { $(this).animate({ 'left': '-=15' }, 3, function() { $(this).animate({ 'left': box_left },3); }); }); }); } } </script> </head> <body> <div id="box"><a href="#">查看效果</a></div> </body> </html>
并不是一个表单登录,但原理如此,只要改造一下即可,下面介绍一下它的实现过程。
一.代码注释:
(1).var box_left=0,声明一个变量并赋值为0。
(2).$(document).ready(function(){}),文档结构完全加载完毕再去执行函数中的代码。
(3).box_left = ($(window).width()-$(‘#box’).width()) / 2,计算出div元素left属性值,此值会使元素水平居中。
(4).$(‘#box’).css({
‘left’:box_left,
‘position’:’absolute’
}),设置div元素的位置。
(5).$(“a”).click(function(){
shock();
return false;
}),为链接a注册click事件处理函数,shock实现了晃动效果,return false可以取消链接a的跳转效果。
(6).function shock(){},此函数可以实现元素的左右晃动效果。
(7).for(i=1;i<7;i++){
$(‘#box’).animate({
‘left’:’-=15′
}, 3, function() {
$(this).animate({
‘left’: ‘+=30’
}, 3, function() {
$(this).animate({
‘left’: ‘-=15’
}, 3, function() {
$(this).animate({
‘left’: box_left
}, 3,);
});
});
});
}使用for循环方式连续执行七次动画。
其实就是不断的通过动画方式设置left属性值。
本文案例为大家展示了《jQuery实现表单登录失败左右晃动代码示例》的代码,若要看代码效果请大家点击“运行代码”按钮。
[code]<!DOCTYPE html> <html> <head> <meta charset=”utf-8″> <title>jQuery实现表单登录失败左右晃动代码示例-搞代码gaodaima.com</title> <style type=”text/css”> body{font:12px Georgia, serif;} a{text-decoration:none;} #box{ width:400px; height:200px; background-color:#ccc; text-align:center } </style> <script src=”http://libs.baidu.com/jquery/1.9.0/jquery.js”></script> <script type=”text/javascript”> var box_left=0; $(document).ready(function(){ box_left = ($(window).width()-$(‘#box’).width()) / 2; $(‘#box’).css({ ‘left’:box_left, ‘position’:’absolute’ }); $(“a”).click(function(){ shock(); return false; }) }); function shock(){ for(i=1;i<7;i++){ $(‘#box’).animate({ ‘left’:’-=15′ }, 3, function() { $(this).animate({ ‘left’: ‘+=30’ }, 3, function() { $(this).animate({ ‘left’: ‘-=15’ }, 3, function() { $(this).animate({ ‘left’: box_left },3); }); }); }); } } </script> </head> <body> <div id=”box”><a href=”#”>查看效果</a></div> </body> </html>[/code]