js实现类似新浪微博首页内容渐显效果的方法
本文实例讲述了js实现类似新浪微博首页内容渐显效果的方法。分享给大家供大家参考。具体分析如下:
要点一:
if(list_li.length>=1){
list.insertBefore(li,list_li[0]);
}else{
list.appendChild(li);
}
从在前面插入新内容,如果没有新内容,就是在后面插入新内容。
要点二:
varheight=li.offsetHeight; li.style.height='0';
取得li的高度,然后再li的高度设置为0,因为高度的变化是从0到现有高度。
要点三:
startrun(li,"height",height,function(){
startrun(li,"opacity","100");
})
先是高度变化,再是透明度变化
最后,上代码:
<!DOCTYPEhtml>
<html>
<head>
<metacharset="gb2312"/>
<title>无标题文档</title>
<style>
<!--
body,ul,li{margin:0;padding:0;font:12px/1.5arial;}
#list{width:400px;margin:10pxauto;}
#listli{list-style:none;padding:5px0;
overflow:hidden;border-bottom:1pxdotted#ccc;
filter:alpha(opacity:0);opacity:0;vertical-align:middle;}
-->
</style>
<script>
<!--
window.onload=function(){
varbtn=document.getElementById("btn");
varcon=document.getElementById("con");
varlist=document.getElementById("list");
varlist_li=list.getElementsByTagName("li");
btn.onclick=function(){
varli=document.createElement("li");
li.innerHTML=con.value;
con.value='';
if(list_li.length>=1){
list.insertBefore(li,list_li[0]);
}else{
list.appendChild(li);
}
varheight=li.offsetHeight;
li.style.height='0';
startrun(li,"height",height,function(){
startrun(li,"opacity","100");
})
}
}
functiongetstyle(obj,name){
if(obj.currentStyle){
returnobj.currentStyle[name];
}else{
returngetComputedStyle(obj,false)[name];
}
}
functionstartrun(obj,attr,target,fn){
clearInterval(obj.timer);
obj.timer=setInterval(function(){
varcur=0;
if(attr=="opacity"){
cur=Math.round(parseFloat(getstyle(obj,attr))*100);
}else{
cur=parseInt(getstyle(obj,attr));
}
varspeed=(target-cur)/8;
speed=speed>0?Math.ceil(speed):Math.floor(speed);
if(cur==target){
clearInterval(obj.timer);
if(fn){
fn();
}
}else{
if(attr=="opacity"){
obj.style.filter="alpha(opacity="+(cur+speed)+")";
obj.style.opacity=(cur+speed)/100;
}else{
obj.style[attr]=cur+speed+"px";
}
}
},30)
}
//-->
</script>
</head>
<body>
<textareaid="con"cols="50"rows="5"></textarea>
<inputid="btn"name=""type="button"value="发布">
<ulid="list">
</ul>
</body>
</html>
希望本文所述对大家的javascript程序设计有所帮助。