当前位置:主页 > 网页前端 > vue >

Vue实现开关按钮拖拽效果

时间:2021-04-19 08:09:15 | 栏目:vue | 点击:

本文实例为大家分享了Vue实现开关按钮拖拽效果的具体代码,供大家参考,具体内容如下

css:

<style>
  .box {
    position: absolute;
    left: 100px;
    top: 100px;
    width: 100px;
    height: 100px;
    background: red;
  }
  .box2 {
    position: absolute;
    left: 400px;
    top: 100px;
    width: 100px;
    height: 100px;
    background: green;
  }
</style>

html:

<div id="app">

  <div class="box" v-drag="isDrag"></div>

  <div class="box2" v-drag:fn.limit.b="isDrag"></div>

  <button @click="isDrag = !isDrag">{{isDrag}}</button>

</div>

js:

<script src="vue.js"></script>
<script>

  // 组件
  Vue.directive('drag', {
    bind(el, {value, arg, modifiers}) {
      console.log(value, arg, modifiers)
      el._value = value;
      el._isDrag = false;
      el.addEventListener('mousedown', function(e) {

        if (!el._value) return;

        el._isDrag = true;
        el._x = e.clientX - el.offsetLeft;
        el._y = e.clientY - el.offsetTop;

        e.preventDefault();
      });
      document.addEventListener('mousemove', function(e) {
        if (el._isDrag) {
          let l = e.clientX - el._x;
          let t = e.clientY - el._y;

          if (modifiers.limit) {
            if (l < 0) {
              l = 0;
            }
            if (t < 0) {
              t = 0;
            }
          }

          el.style.left = l + 'px';
          el.style.top = t + 'px';
        }
      });
      document.addEventListener('mouseup', function(e) {
        el._isDrag = false;
      });
    },

    componentUpdated(el, {value}) {
      console.log('更新了', value);
      el._value = value;
    }
  });

  let app = new Vue({
    el: '#app',
    data: {
      isDrag: false
    }
  });


</script>

您可能感兴趣的文章:

相关文章