点击扩展或缩小文本框效果代码:
文本框自然为填写内容而存在,如果能够人为的调整文本框的尺寸以适应内容的多少可以有效的提高网页的人性化程度,为网站增色不少,下面就简单介绍一下如何实现此效果,代码如下:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="author" content="http://www.softwhy.com/" /> <title>点击扩展或缩小文本框效果代码-蚂蚁部落</title> <script type="text/javascript" src="http://www.softwhy.com/mytest/jQuery/jquery-1.8.3.js"></script> <script type="text/javascript"> $(function(){ var $comment = $('#comment'); $('.bigger').click(function(){ if(!$comment.is(":animated")){ if( $comment.height() < 500 ){ $comment.animate({ height : "+=50" },400); } } }) $('.smaller').click(function(){ if(!$comment.is(":animated")){ if( $comment.height() > 50 ){ $comment.animate({ height : "-=50" },400); } } }); }); </script> </style> </head> <body> <textarea rows="10" cols="40" id="comment">请输入内容..</textarea> <button class="bigger">点击放大</button><button class="smaller">点击缩小</button> </body> </html>
以上代码实现了我们想要的效果,点击相应按钮能够实现文本框的扩展和缩小效果,下面简单介绍一下实现过程:
一.实现原理:
当点击按钮的时候通过animate()函数以动画的形式调整调整文本框的尺寸。尺寸不是随意调整的,而是设置了一个上线和下线,当超过上限,尺寸就不会再增加,当小于下限,尺寸也不会再减少。
二.代码注释:
1.$(function(){},当文档结构加载完成之后再去执行函数中的代码。
2.var $comment = $('#comment'),获取文本框对象。
3.$('.bigger').click(function(){},为class属性值为bigger的按钮绑定click事件处理函数。
4.if(!$comment.is(":animated")){}判断文本框是否处于动画状态。关于is()可以参阅 jQuery的is()方法。
5.if( $comment.height() < 500 ){},判断文本框高度是否小于500px,如果小于则会扩大尺寸。
6.$comment.animate({ height : "+=50" },400),重新设置高度,在原有的基础上加50。关于animate()函数参阅 jQuery的animate()方法。
原文地址是:http://www.softwhy.com/forum.php?mod=viewthread&tid=7988
更多内容可以参阅:http://www.softwhy.com/jquery/