vue2设置横向滚动指令

图片横向滑动展示效果

在这活动里插入图片描述在这里插入图片描述

创建directives.js文件

// 横向列表拖拽
const draggleScrollX = {
    inserted(el, binding) {
        let isDragging = false;
        let startX = 0;
        let scrollLeft = 0;
        el.classList.add("draggle-horizontal");

        // 添加监听事件-鼠标按下
        const onMouseDown = (event) => {
            isDragging = true;

            // 鼠标位置和初始滚动位置
            startX = event.pageX - el.offsetLeft;
            scrollLeft = el.scrollLeft;

            el.style.cursor = "grabbing";
            el.style.userSelect = "none";
        };

        // 鼠标离开或者松开
        const onMouseUpOrLeave = () => {
            isDragging = false;
            el.style.cursor = "auto";
            el.style.userSelect = "";

            setTimeout(() => {
                const childrenNodes = Array.from(el.children);

                childrenNodes.forEach((childrenNode) => {
                    childrenNode.style.pointerEvents = "all";
                });

                // 粘滞定位
                if (binding.modifiers.snap) {
                    // const maxScrollWidth = el.scrollWidth - el.clientWidth; // 最大滚动宽度
                    const scrollStep = [0]; // 每个值的滚动step
                    childrenNodes.forEach((childrenNode, index) => {
                        const rectWidth = childrenNode.getBoundingClientRect().width;
                        const style = window.getComputedStyle(childrenNode);
                        const nodeWidth = rectWidth + parseFloat(style.marginLeft) + parseFloat(style.marginRight);

                        if (index !== childrenNodes.length - 1) {
                            scrollStep[index + 1] = nodeWidth + scrollStep[index];
                        }
                    });

                    const diffScroll = scrollStep.map((step) => Math.abs(step - el.scrollLeft));
                    const minDiffIndex = diffScroll.indexOf(Math.min(...diffScroll));

                    el.scrollTo({ left: scrollStep[minDiffIndex], behavior: "smooth" });
                }
            }, 100);
        };

        // 鼠标移动
        const onMouseMove = (event) => {
            if (!isDragging) return;

            const x = event.pageX - el.offsetLeft;
            const walk = x - startX;
            el.scrollLeft = scrollLeft - walk;

            Array.from(el.children).forEach((childrenNode) => {
                childrenNode.style.pointerEvents = "none";
            });

            // 触发自定义事件,传递当前滚动位置  不需要可以不用这部分代码
            const scrollEvent = new CustomEvent("draggle-scroll-x", {
                detail: {
                    scrollLeft: el.scrollLeft,
                },
            });
            el.dispatchEvent(scrollEvent);
        };

        // 设置初始样式
        el.style.cursor = "auto";
        el.style.overflow = "auto";
        el.style.scrollbarWidth = "none";
        el.style.cssText += "::-webkit-scrollbar { display: none; }";

        el._dragEvents = {
            onMouseDown,
            onMouseUpOrLeave,
            onMouseMove,
        };

        el.addEventListener("mousedown", onMouseDown);
        el.addEventListener("mousemove", onMouseMove);
        el.addEventListener("mouseup", onMouseUpOrLeave);
        el.addEventListener("mouseleave", onMouseUpOrLeave);
    },

    unbind(el) {
        const { onMouseDown, onMouseUpOrLeave, onMouseMove } = el._dragEvents || {};

        el.removeEventListener("mousedown", onMouseDown);
        el.removeEventListener("mousemove", onMouseMove);
        el.removeEventListener("mouseup", onMouseUpOrLeave);
        el.removeEventListener("mouseleave", onMouseUpOrLeave);
    },
};
export { draggleScrollX };

.vue文件内使用 vue2

import { draggleScrollX } from "../../utils/directives.js";
export default {
  directives: {
    draggleScrollX: draggleScrollX,
  },
}

最外部的div上面使用

<div class="swiper" v-draggle-scroll-x @draggle-scroll-x="handleScroll">
</div>

@draggle-scroll-x=“handleScroll” 这个函数是为了获取到滚动的距离 也就是滚动定位 可以做一些处理

handleScroll(event) {
      const scrollLeft = event.detail.scrollLeft;
      console.log("滚动的距离",scrollLeft);
       }

.snap加了吸附粘滞的了 但是效果不是特别明显

<div class="swiper" v-draggle-scroll-x.snap @draggle-scroll-x="handleScroll">
</div>
Vue中实现图片横向滚动通常可以通过创建一个滚动容器,并利用CSS样式来实现横向滚动效果。以下是一个基本的实现方法: 1. 首先,在Vue组件的模板中创建一个用于滚动的`<div>`容器,并设置其宽度以及溢出隐藏(overflow: hidden)属性。 2. 在该容器内部,创建另一个`<div>`,其宽度大于容器宽度,并设置`overflow-x: scroll`属性来实现横向滚动。 3. 将需要横向滚动显示的图片放置在内部`<div>`中。 4. 使用Vue的数据绑定和条件渲染等特性,动态地向内部`<div>`中添加图片元素。 以下是一个简单的示例代码: ```html <template> <div class="scroll-container" ref="scrollContainer"> <div class="scroll-content" ref="scrollContent"> <img v-for="(image, index) in images" :key="index" :src="image" alt="滚动图片" > </div> </div> </template> <style> .scroll-container { width: 300px; overflow: hidden; white-space: nowrap; } .scroll-content { display: inline-block; width: auto; /* 根据实际图片数量和宽度调整 */ overflow-x: scroll; } img { width: 100px; /* 单个图片的宽度 */ height: 100px; /* 单个图片的高度 */ margin-right: 10px; /* 图片之间的间距 */ vertical-align: top; } </style> <script> export default { data() { return { images: [ 'path/to/image1.jpg', 'path/to/image2.jpg', // 更多图片路径... ] }; } }; </script> ``` 在上面的示例中,`.scroll-container` 是用于控制滚动的外部容器,`.scroll-content` 是实际包含图片的内部滚动元素。通过设置`overflow-x: scroll`属性,可以使得内部`<div>`元素在水平方向上滚动。图片通过`v-for`指令动态渲染,每张图片占据一定的宽度和高度。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值