文字跑马灯效果
文字跑马灯
笔者在开发移动端,因为移动端的屏幕较小,在展示文字的时候,比如说一个区域有5个文字,效果图展示没有问题,但是实际的数据可能是10个或者更多文字,如果折行就不美观,不折行又显示不下。加上省略号看起来美观些,但是还是看不全文字,所以跑马灯效果是一个很好的解决方案。
代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>跑马灯效果</title> </head> <body> <div class="div-wrap" style="width:100px;"></div> </body> <script> /** * @desc 文字跑马灯 * @param {domNode} [Element] ele 文字外容器dom * @param {offSetLeft} [Number] offSetLeft 文字跑动距离左侧容器距离 * @param {text} [String] 文字 */ function RunChar(ele, offSetLeft, text) { this.ele = ele; this.text = text; this.init = function() { let nSpan = document.createElement('span'); let nText = document.createTextNode(text); nSpan.appendChild(nText); this.ele.appendChild(nSpan); // css this.ele.style['white-space'] = 'nowrap'; this.ele.style['overflow'] = 'hidden'; nSpan.style['display'] = 'inline-block'; let wrapWidth = Math.ceil(parseFloat(this.getStyle(this.ele, 'width'))); let spanWidth = Math.ceil(parseFloat(this.getStyle(nSpan, 'width'))); if(spanWidth > wrapWidth) { let w = spanWidth - wrapWidth; let moveVal = 0; setInterval(function() { nSpan.style.transform = `translateX(${moveVal--}px)`; if(moveVal <= -(w+offSetLeft)) moveVal = offSetLeft; }, 100); } } this.getStyle = function(element, attr) { var computed; if(element.currentStyle) { computed = element.currentStyle; } else { computed = window.getComputedStyle(element, false); } return computed.getPropertyValue( attr ) || computed[ attr ]; } this.init(); } new RunChar(document.querySelector('.div-wrap'), 100, '文字跑马灯效果'); </script> </html>
|