《锋利的JS》之 多行文本框高度变化
这是《锋利的JQ》里第五章的第二个实例,主要知识点是涉及到动画,动画在前面的博文里已有提到,所以这一个实例就放代码,不解释,详情请移步:《锋利的JS》之 轮播效果和动画。
结构代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title></title> <style type="text/css"> *{ margin:0; padding:0; font: normal 12px/17px Arial;} .msg{ width:300px; margin:100px;} .msg_caption{ width:100%;overflow:hidden; margin-bottom:1px;} .msg_caption span{ display:block; float:left; margin:0 2px; padding:4px 10px; background:#898989; cursor:pointer; color:white;} .msg textarea{ width:300px; height:100px; border:1px solid #000;} </style> </head> <body> <form action="" method="post"> <div class="msg"> <div class="msg_caption"> <span class="bigger">放大</span> <span class="smaller">缩小</span> </div> <div> <textarea id="comment" rows="8" cols="20">多行文本框高度变化.多行文本框高度变化.多行文本框高度变化.多行文本框高度变化.多行文本框高度变化.多行文本框高度变化.多行文本框高度变化.多行文本框高度变化.多行文本框高度变化.</textarea> </div> </div> </form> </body> </html>
JQ代码:
$(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); } } }); })
我仿写的JS代码:
window.onload = function(){ var bigger = getElementsByClassName("bigger")[0]; var smaller = getElementsByClassName("smaller")[0]; var comment = document.getElementById("comment"); var t; bigger.onclick = function(){ if(t) clearInterval(t); if(comment.offsetHeight < 500){ t = animate(comment,{height:comment.offsetHeight},{height:50},400,Quad); } } smaller.onclick = function(){ if(t) clearInterval(t); if(comment.offsetHeight > 50){ t = animate(comment,{height:comment.offsetHeight},{height: -50},400,Quad); } } } function animate(obj,start,alter,dur,fx){ var curTime = 0; var interval = setInterval(function(){ if(curTime >= dur){ clearInterval(interval); } for(var i in start){ obj.style[i] = fx(start[i],alter[i],curTime,dur) + "px"; } curTime += 50; },50); return interval; } function Quad(start,alter,curTime,dur){ return start+Math.pow(curTime/dur,2)*alter; } function getElementsByClassName(className,node){ node = node || document; if(node.getElementsByClassName){ return node.getElementsByClassName(className); } var eles = node.getElementsByTagName('*'); var reg = []; for(var i = 0,l = eles.length; i < l; i++){ if(hasClass(className,eles[i])){ reg.push(eles[i]); } } return reg; } function hasClass(className,node){ var eles = node.className.split(/\s+/); for(var i = 0,l = eles.length; i < l; i++){ if(eles[i] == className){ return true; } } return false; }
最终运行效果: