1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title>文本内容自动回滚</title> 6 </head> 7 8 <body> 9 <h2>文本框中的文字自动回滚效果</h2> 10 <div id="rollContent" data-rwidth="100" data-rheight="100" class="roll_content"> 11 aaaaaaaaaaa 12 bbbbbbbbbbb 13 ccccccccccc 14 ddddddddddd 15 eeeeeeeeeee 16 fffffffffff 17 ggggggggggg 18 rrrrrrrrrrr 19 ttttttttttt 20 wwwwwwwwwww 21 </div> 22 <script type="text/javascript"> 23 window.onload=function(){ 24 var _rollContent=document.getElementById("rollContent"), 25 _div=_rollContent.innerHTML; 26 27 var setCss=function(_this,cssOption){//设置样式 28 //检测节点类型 29 if(!_this||_this.nodeType===3||_this.nodeType===8||!_this.style){ 30 return console.log("bug"); 31 } 32 for(var cs in cssOption){//遍历样式 33 _this.style[cs]=cssOption[cs]; 34 } 35 return _this; 36 37 }; 38 39 _rollContent.innerHTML="<div id='rollContent_roll'>"+_div+"</div>"; 40 41 setCss(_rollContent,{ 42 "position":"relative", 43 "overflow":"hidden", 44 "wordWrap":"break-word", 45 "wordBreak":"break-all", 46 "width":_rollContent.getAttribute("data-rwidth")+"px", 47 "height":_rollContent.getAttribute("data-rheight")+"px", 48 "border":"2px solid red" 49 }); 50 51 var _timeRoll=document.getElementById("rollContent_roll"); 52 var _h=_timeRoll.offsetHeight; 53 54 timeoutRoll=function(){//修改top值 55 var _h=_timeRoll.offsetHeight, 56 _t=parseInt(_timeRoll.style.top,10); 57 //是否将top设置为0 58 var _tt=_h>Math.abs(_t)||_t>=0?_t-10:(_h||0); 59 setCss(_timeRoll,{ 60 "top":_tt+"px", 61 "border":"1px solid blue" 62 }); 63 setTimeout(timeoutRoll,200);//设置定时器 64 }; 65 //判断滚动高度是否大于data-rheight 66 if(_h>_rollContent.getAttribute("data-rheight")){ 67 timeoutRoll(); 68 setCss(_timeRoll,{ 69 "position":"relative", 70 "top":"0px" 71 }); 72 } 73 74 }; 75 </script> 76 </body> 77 </html>