反转基因福娃 发表于 2024-7-11 08:37:40

怎样在Vue中实现拖拽功能?

Vue.js是一款流行的JavaScript框架,用于构建用户界面。此中一个常见的需求是在Vue中实现拖拽功能,让用户可以通过拖拽元素来进行交互。今天,我们就来学习怎样在Vue中实现这一功能。
起首,我们需要明白拖拽功能的根本原理:监听鼠标变乱、实时更新拖拽元素的位置,末了在合适的时机制止拖拽并更新元素位置。在Vue中,我们可以通过绑定相关变乱来实现这一功能。


效果展示

https://i-blog.csdnimg.cn/direct/95f926370de8424ab24c4665523a890c.png
 代码展示

<!DOCTYPE HTML>
<html>

<head>
    <title>拖放示例-文本</title>
</head>
<style>
.src {
    display: flex;
}

.dropabled {
    flex: 1;
}

.txt {
    color: green;
}

.img {
    width: 100px;
    height: 100px;
    border: 1px solid gray;
}

.target {
    width: 200px;
    height: 200px;
    line-height: 200px;
    text-align: center;
    border: 1px solid gray;
    color: red;
}
</style>

<body>
    <div class="src">
      <div class="dragabled">
            <div class="txt" id="txt">
                所有的图片都可拖拽。
                <p draggable="true">
                  <img class="img" id="tupian1" src="1670483208231593.jpg" alt="图片1" />
                  <img class="img" id="tupian2" src="R-C.jfif" alt="图片2" />
                  </p>
            </div>
         
         
      </div>
      <div id='target' class="dropabled target">拖到这</div>
    </div>
    <script>
      var dragSrc = document.getElementById('txt')
      var target = document.getElementById('target')

      dragSrc.ondragstart = handle_start
      dragSrc.ondrag = handle_drag
      dragSrc.ondragend = handle_end

      function handle_start(e) {
          console.log('拖拽1')
      }

      function handle_drag() {
            console.log('拖拽2')
      }

      function handle_end() {
      console.log('拖拽2')
      console.log('拖拽2')
    }

      target.ondragenter = handle_enter
      target.ondragover = handle_over
      target.ondragleave = handle_leave

      target.ondrop = handle_drop

      function handle_enter(e) {
            console.log('拖拽2')
            // 阻止浏览器默认行为
            e.preventDefault()
      }

      function handle_over(e) {
            console.log('拖拽2')
            // 阻止浏览器默认行为
            e.preventDefault()
      }

      function handle_leave(e) {
            console.log('拖拽2')
            // 阻止浏览器默认行为
            // e.preventDefault()
      }

      function handle_drop(e) {
            console.log('拖拽')
            var t = Date.now()
            target.innerHTML = ''
            target.append(t + '-拖拽')
            e.preventDefault()
      }
    </script>
</body>

</html>

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: 怎样在Vue中实现拖拽功能?