js implements a method similar to the sina weibo home page for gradual effect

  • 2020-05-27 04:12:04
  • OfStack

This article describes the example of js to achieve similar sina weibo home page content gradual effect method. Share with you for your reference. The specific analysis is as follows:

Point 1:


if(list_li.length>=1){
list.insertBefore(li,list_li[0]);
}else{
list.appendChild(li);
}

Insert new content from the front and, if there is no new content, insert new content from the back.

Point 2:


var height=li.offsetHeight;
li.style.height='0';

Get the height of li, and then set the height of li to 0, because the height changes from 0 to the existing height.

Point 3:


startrun(li,"height",height,function(){
startrun(li,"opacity","100");
})

First the height, then the transparency

Finally, add the code:


<!DOCTYPE html>
<html>
<head>
<meta charset="gb2312" />
<title> Headless document </title>
<style>
<!--
body,ul,li{margin:0; padding:0; font:12px/1.5 arial;}
#list{width:400px; margin:10px auto;}
#list li{list-style:none; padding:5px 0 ;
overflow:hidden; border-bottom:1px dotted #ccc;
filter:alpha(opacity:0); opacity:0; vertical-align:middle;}
-->
</style>
<script>
<!--
window.onload = function(){
 var btn = document.getElementById("btn");
 var con = document.getElementById("con");
 var list = document.getElementById("list");
 var list_li = list.getElementsByTagName("li");
 btn.onclick = function(){
  var li = document.createElement("li");
  li.innerHTML = con.value;
  con.value='';
  if(list_li.length>=1){
   list.insertBefore(li,list_li[0]);
  }else{
   list.appendChild(li);
  }
  var height=li.offsetHeight;
  li.style.height='0';
  startrun(li,"height",height,function(){
   startrun(li,"opacity","100");
  })
 }
}
function getstyle(obj,name){
 if(obj.currentStyle){
  return obj.currentStyle[name];
 }else{
  return getComputedStyle(obj,false)[name];
 }
}
function startrun(obj,attr,target,fn){
 clearInterval(obj.timer);
 obj.timer = setInterval(function(){
  var cur = 0;
  if(attr == "opacity"){
   cur = Math.round(parseFloat(getstyle(obj,attr))*100);
  }else{
   cur = parseInt(getstyle(obj,attr));
  }
  var speed = (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>
<textarea id="con" cols="50" rows="5"></textarea>
<input id="btn" name="" type="button" value=" release ">
<ul id="list">
</ul>
</body>
</html>

I hope this article has helped you with your javascript programming.


Related articles: