1. 程式人生 > 其它 >vue自定義指令實現拖拽元素改變元素的寬度

vue自定義指令實現拖拽元素改變元素的寬度

// 自定義指令
  directives: {
    drag: {
      inserted: function (el) {
        const dragDom = el;
        dragDom.style.cursor = "e-resize";
        dragDom.onmousedown = (e) => {
          // 滑鼠按下,計算當前元素距離可視區的距離
          const disX = e.clientX;
          const w = dragDom.clientWidth;
          const minW 
= 240; const maxW = 600; var nw; document.onmousemove = function (e) { // 通過事件委託,計算移動的距離 const l = e.clientX - disX; // 改變當前元素寬度,不可超過最小最大值 nw = w + l; nw = nw < minW ? minW : nw; nw = nw > maxW ? maxW : nw; dragDom.style.width
= `${nw}px`; }; document.onmouseup = function (e) { document.onmousemove = null; document.onmouseup = null; }; }; }, }, },
//在需要拖動的元素上新增自定義指令
      <div class="s-l" v-drag>