如何编写一个高性能的无缝滚动插件?

时间:2019-02-21 01:03:03

标签: javascript vue.js

<pre>
<code>
    <template>
        <div class="seamless-group" ref="group">
            <ul>
                <li v-for="item in data" :key="item._id">
                    <img :src="item.pic" />
                </li>
            </ul>
        </div>
    </template>
    <script>
    export default {
        props: {
            data: {
                default: [],
                type: Array
            }
        },
        mounted() {
            this.seamlessScroll({
                pd: 40,
                gridWidth: 556
            });
        },
        methods: {
            seamlessScroll(options = {}) {
                let defaultConfig = {
                    pd: 20,
                    gridWidth: null,
                    xCache: 0
                };
                options = Object.assign(defaultConfig,options);
                let el = this.$refs.group.querySelector("ul");
                let parentContainerWidth = 0;
                let imgContainers = el.querySelectorAll("li");
                let count = imgContainers.length;
                if(!options.gridWidth) {
                    for(let i = 0; i < count ; i++) {
                        parentContainerWidth += imgContainers[i].getBoundingClientRect().width;
                        el.insertAdjacentElement("beforeend",imgContainers[i].cloneNode(true));
                    }
                }else {
                    for(let i = 0; i < count ; i++) {
                        parentContainerWidth += options.gridWidth;
                        el.insertAdjacentElement("beforeend",imgContainers[i].cloneNode(true));
                    }
                }
                parentContainerWidth = parentContainerWidth + count * options.pd;
                console.log(parentContainerWidth);
                options.xCache = el.querySelector("li:first-child").offsetLeft;
                let fz_left = parentContainerWidth * -1;
                scroll();
                function scroll() {
                    if(options.xCache <= fz_left) {
                        options.xCache = 0;
                    }
                    options.xCache -= 1;
                    el.style.transform = "translateX(" + options.xCache.toString() + "px)";
                    window.requestAnimationFrame(scroll);
                }
            }
        }
    }
    </script>

    <style lang="less">
        .seamless-group {
            position: relative;
            overflow: hidden;
            ul {
                list-style: none;
                padding: 0;
                display: flex;
                li {
                    width: 556px;
                    margin-right: 40px;
                }           
            }
        }
    </style>

</code>

这是一个vue组件代码,我尝试对其进行封装,我使用了翻译移动父容器,不知道这是否是适当的方法吗?是否存在问题,例如屏幕宽度太大,第二个滚动内容无法完全显示涵盖了如何有效地解决问题?(这是vue.js组件的代码)。 这是我的代码:

0 个答案:

没有答案