js realizes the effect of text horse race

  • 2021-07-24 09:21:51
  • OfStack

This example will realize the effect of text ticker: the text exceeds the display width and automatically scrolls to the left every 1s. Don't say much, please see the code


<!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 Realize that the text exceeds the display width every interval 1s Automatic left scroll display </title>
  <style type="text/css">
    *{ margin:0; padding:0;}
    body{font:12px/1 ' Microsoft Yahei ';}
    .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"> Text scrolls to the left if it exceeds its width. Text scrolls to the left if it exceeds its width. </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>

Related articles: