首页 > 代码库 > css3 transition 和 animation实现走马灯

css3 transition 和 animation实现走马灯

这段时间在做一个App,H5的开发。页面上有公告 以走马灯的形式显示出来。

在开始直接用的marquee标签,后来发现在ios客户端,走马灯移动不够平滑,有抖动现象。

对于有强迫症的我而言是无法忍受的,后来就用js来写,发现andriod和ios客户端 的走马灯移动都不平滑,会抖动。

后来想到了可以用css3的transition和animation来写,分享一下代码!

transition写法

<!DOCTYPE html><html><head><meta charset="UTF-8"><title>marquee</title><style type="text/css">body{padding: 0;margin: 0;}#demo{width: 100%;height: 50px;background: #eee;position: fixed;}#demo>#spa{word-break:keep-all;white-space:nowrap;position: absolute;left: 100%;font-size: 30px;line-height: 50px;}</style></head><body>    <div id="demo"><span id=‘spa‘ >走马灯效果</span></div></body><script type="text/javascript">     var spa = document.getElementById("spa");     var spaw = spa.offsetWidth;     var bodyw = document.body.clientWidth;     var w = 0-(spaw+bodyw);     spa.style.transform = ‘translate(‘ + w + ‘px, 0px)‘;     spa.style.transition = ‘transform 5s linear‘;     window.setInterval(function(){          spa.style.transform = ‘translate(0px, 0px)‘;          spa.style.transition = ‘transform 0s linear‘;          window.setTimeout(function(){               spa.style.transform = ‘translate(‘ + w + ‘px, 0px)‘;               spa.style.transition = ‘transform 5s linear‘;          },100)     },5000)</script></html>

注意的是在iphone4s 上 ,transition属性建议分开写,直接写transition上设置四个属性的话,ihone4s的浏览器不能识别。

animation写法

<!DOCTYPE html><html><head><meta charset="UTF-8"><title>marquee</title><style type="text/css">#demo{width: 100%;height: 50px;background: #eee;position: fixed;}#demo>span{word-break:keep-all;white-space:nowrap;position: absolute;left: 100%;font-size: 30px;line-height: 50px;}#demo>.a{-webkit-animation:demo 5s infinite;-webkit-animation-timing-function:linear;}</style><style id=‘asty‘></style></head><body>    <div id="demo"><span id=‘spa‘ class=‘a‘>走马灯效果</span></div></body><script type="text/javascript">    var spa = document.getElementById("spa");    var width = 0-(spa.offsetWidth);    var style = document.getElementById("asty");    style.innerHTML = ‘@-webkit-keyframes demo{from {left: 100%;}to {left: ‘+width+‘px;}}‘;    spa.className = ‘a‘;</script></html>

 

css3 transition 和 animation实现走马灯