九八野马 2022-05-04 13:55:59
用Vue实现无缝轮播好像比较省事:
用transition-group
来显示图片的位置,
Vue中的过渡有4种状态:
enter -> enter-to, leave ->leave-to
如果向左移动,那么enter从 translateX(-100%)
开始,到 translateX(0)
结束,leave从translateX(0)
开始,到translateX(100%)
结束,向右移动则反过来。
<!DOCTYPE html> <html> <head> <title></title> <script src="https://cdn.bootcss.com/vue/2.6.10/vue.min.js"></script> <style type="text/css"> #app { display: flex; align-items: center; margin: auto; width: 200px; } ul { list-style-type: none; position: relative; width: 100px; height: 100px; box-sizing: border-box; padding: 0; margin: auto; overflow: hidden; } li { width: 100px; height: 100px; position: absolute; } #one { background: yellow; } #two { background: black; } #three { background: pink; } #four { background: orange; } .right_animation-enter, .left_animation-leave-to { transition: all .3s ease; transform: translateX(-100px); } .right_animation-leave-to, .left_animation-enter { transition: all .3s ease; transform: translateX(100px); } .right_animation-enter-to, .right_animation-leave, .left_animation-enter-to, .left_animation-leave { transition: all .3s ease; transform: translateX(0); } </style> </head> <body> <div> <button @click="turn('left')">左</button> <transition-group tag="ul" :name="direction=='left' ? 'left_animation' : 'right_animation'"> <li v-for="(img,index) in imgs" :id="img" :key="index" v-show="current_index===index"> </li> </transition-group> <button @click="turn('right')">右</button> </div> </body> <script> new Vue({ el: '#app', data: { imgs: ['one', 'two', 'three'], direction: 'left', current_index: 0 }, methods: { turn: function (side) { this.direction = side if (side == 'left') { this.current_index -= 1 if (this.current_index < 0) { this.current_index = this.imgs.length - 1 } } else { this.current_index += 1 if (this.current_index === this.imgs.length) { this.current_index = 0 } } } }}) </script> </html>
- 共 1 页
- 1
这里似乎有个问题,就是如果使用定时器的话,在 500ms 后执行的始终是前 500ms 内触发的第一个函数 fn,之后的在 500ms 内触发函数都将被丢弃,这样的话,fn 里获取的参数 arguments 可能不准确。应该以 500ms 内触发的最后一个函数为准,而不是第一个函数。
第 3 题:什么是防抖和节流?有什么区别?如何实现?