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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM