這段時間在做一個App,H5的開發。頁面上有公告 以走馬燈的形式顯示出來。
在開始直接用的marquee標簽,后來發現在ios客戶端,走馬燈移動不夠平滑,有抖動現象。
對于有強迫癥的我而言是無法忍受的,后來就用js來寫,發現andriod和ios客戶端 的走馬燈移動都不平滑,會抖動。
css輪播圖代碼?后來想到了可以用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屬性??