布局容器布局下的左右托拽指令

vue+elementUI 项目 实现 Container 布局容器布局下的左右托拽指令

话不多说上代码

import Vue from "vue";
const resize = {
  //被绑定元素插入父节点时调用 (仅保证父节点存在,但不一定已被插入文档中)。
  inserted(el, binding, vnode, oldVnode) {
    //创建一个定位的节点定位到要托拽的节点上
    const resize: HTMLElement = document.createElement("div");
    resize.innerText = "✌";
    const style = {
      position: "absolute",
      top: "0%",
      right: "0",
      display: "flex",
      flexDirection: "column",
      alignItems: "center",
      justifyContent: "center",
      width: "10px",
      height: "100%",
      overflow: "hidden",
      cursor: "e-resize",
    };
    for (const key in style) {
      if (resize.style.hasOwnProperty(key)) {
        resize.style[key] = style[key];
      }
    }
    el.appendChild(resize);
    //获取binding参数
    const { container = false, percent = 0.5 } = binding.value;
    //容器
    let containerNode = container
      ? document.querySelector(container)
      : el.parentElement;
    //容器宽度
    let clientWidth = containerNode.clientWidth;
    //要托拽节点的位置参数
    let targetPosition = el.getBoundingClientRect();
    //最大可托拽宽度
    let maxWidth = clientWidth * percent;
    //托拽事件
    const handleMove = (e) => {
      let targetWidth = e.clientX - targetPosition.right + targetPosition.width;
      targetWidth > maxWidth ? (targetWidth = maxWidth) : null;
      el.style.flex = `0 0 ${targetWidth}px`;
    };
    //鼠标按下触发托拽
    resize.addEventListener("mousedown", (e) => {
      containerNode.addEventListener("mousemove", handleMove);
    });
    //鼠标抬起清除事件
    containerNode.addEventListener("mouseup", (e) => {
      containerNode.removeEventListener("mousemove", handleMove);
    });
  },
};
Vue.directive("resize", resize);
posted @ 2021-10-11 13:34  __Bowen  阅读(114)  评论(0编辑  收藏  举报