手写一个文字横向滚动组件

利用transition实现一个横向滚动组件:

<!DOCTYPE html>
<html>

<head>
 <meta charset="utf-8">
    <meta name="format-detection" content="telephone=no" />
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no" />
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache, no-store, must-revalidate">
    <meta http-equiv="expires" content="0">
    <style type="text/css">
        body {}
      
        .container {
            height: auto;
            width: 300px;
            border: 1px solid red;
            transition: height 1px 0.2s;
            overflow:hidden;
            display:flex;
        }
         .container>div {
           flex-shrink:0;
          
         }
        .son {
            width: 300px;
            height: 40px;
        }
        
       
    </style>
</head>

<body>
    <div class="container">
    </div>
    </script>
    <script>
      let list = [
       '错过你,我将永不落地,但我丢不掉自己的翅膀',
       '错过你,我将无法前行,但我只能选择仰望你的轮廓',
       '错过你,我将永不落地,但我丢不掉自己的翅膀',
'错过你,我将无法前行,但我只能选择仰望你的轮廓'
] function StartAnimation(list, containerdom, thespeed = 300) { let container = document.getElementsByClassName(containerdom)[0] // 将文字作为内容填充到div中 并将创建的div放到container里面 for (let j = 0; j < list.length; j++) { let div = document.createElement('div'); div.innerHTML = list[j] div.style['white-space'] = 'nowrap' container.appendChild(div) } // 获取容器的子类 获取滚动长度 let childlist = container.children; setTimeout(() => { let containerlength = Number(getComputedStyle(container, null).width.split('px')[0]) let alllength = 0 for (let j = 0; j < childlist.length; j++) { // 采用getComputedStyle获取div的真实宽度 let white = Number(getComputedStyle(childlist[j], null).width.split('px')[0]) alllength += white } // 如果alllength的宽度小于容器的宽度 则不需要轮播 if(alllength<containerlength) { return false } // 滚动速度 let speed = thespeed let oldtime = (alllength) / speed let time = oldtime // 利用transition来实现滚动效果 childlist[0].style.transition = `margin-left ${time}s linear` childlist[0].style['margin-left'] = '0px' console.log(time) // 利用setTimeout来实现延时递归 let f = (s, isbegin) => { if (s == 'start') { console.log('开始') // 设置transition为margin-left childlist[0].style.transition = `margin-left ${oldtime}s linear` childlist[0].style['margin-left'] = `-${alllength}px` time = oldtime } if (s == 'end') { childlist[0].style.transition = 'none' childlist[0].style['margin-left'] = `0px` // 0.1 缓冲时间 将意味着重新开始滚动之后 将会停留100ms time = 0.1 console.log('结束') } setTimeout(() => { f(s == 'start' ? 'end' : 'start') }, time * 1000) } f('start', 1) console.log(alllength) }, 20) } StartAnimation(list,'container',200) </script> </body> </html>

 

 

posted @ 2021-12-22 10:39  wangnima666  阅读(79)  评论(0)    收藏  举报