js实现文字跑马灯效果
时间:2021-09-09 09:51:28|栏目:JavaScript代码|点击: 次
本示例将实现文字跑马灯效果:文字超过显示宽度每间隔1s自动向左滚动显示,话不多说,请看代码
<!doctype html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0"/> <meta name="format-detection" content="telephone=no,email=no,date=no,address=no"> <title>js实现文字超过显示宽度每间隔1s自动向左滚动显示</title> <style type="text/css"> *{ margin:0; padding:0;} body{font:12px/1 '微软雅黑';} .wrapper{font-size: 0.85rem; color: #333; padding-top: 0.75rem; margin: 0 0.75rem; white-space: nowrap; overflow: hidden;width: 300px;} .inner{ width:1000px;overflow:hidden;} .inner p{ display:inline-block;} </style> </head> <body> <div id="wrapper" class="wrapper"> <div class="inner"> <p class="txt">文字如果超出了宽度自动向左滚动文字如果超出了宽度自动向左滚动。</p> </div> </div> <script> var wrapper = document.getElementById('wrapper'); var inner = wrapper.getElementsByTagName('div')[0]; var p = document.getElementsByTagName('p')[0]; var p_w = p.offsetWidth; var wrapper_w = wrapper.offsetWidth; window.onload=function fun(){ if(wrapper_w > p_w){ return false;} inner.innerHTML+=inner.innerHTML; setTimeout("fun1()",2000); } function fun1(){ if(p_w > wrapper.scrollLeft){ wrapper.scrollLeft++; setTimeout("fun1()",30); } else{ setTimeout("fun2()",2000); } } function fun2(){ wrapper.scrollLeft=0; fun1(); } </script> </body> </html>