正巧在之前面試中遇到問實現(xiàn)拖拽效果
創(chuàng)新互聯(lián)公司是專業(yè)的南陵網(wǎng)站建設(shè)公司,南陵接單;提供網(wǎng)站設(shè)計、成都網(wǎng)站建設(shè),網(wǎng)頁設(shè)計,網(wǎng)站設(shè)計,建網(wǎng)站,PHP網(wǎng)站建設(shè)等專業(yè)做網(wǎng)站服務(wù);采用PHP框架,可快速的進行南陵網(wǎng)站開發(fā)網(wǎng)頁制作和功能擴展;專業(yè)做搜索引擎喜愛的網(wǎng)站,專業(yè)的做網(wǎng)站團隊,希望更多企業(yè)前來合作!
當(dāng)時面試的時候簡單回答了實現(xiàn)的方式與邏輯。
現(xiàn)在閑來無事,把這個東西實現(xiàn)了一下。
原理很簡單,寫的很方便。
數(shù)據(jù)驅(qū)動,建立一個數(shù)組,數(shù)組初始長度為1
拖動觸發(fā)時,添加一個對象到數(shù)組中,拖動的是下標(biāo)為0的對象,新建的還在原來位置放著,等待下次拖動。
話不多說,上代碼
<template> <div class="view"> <div class="x" @mousedown="move($event,index)" v-for="(x,index) in i"> <span v-if="index+1 !== i.length">{{index+1}}</span> <input v-model="x.input"> </div> {{i}} </div> </template> <script> export default { name: "index", data(){ return{ positionX:0, positionY:0, i:[ {input:''} ] } }, methods:{ move(e,x){ let odiv = e.target; //獲取目標(biāo)元素 //算出鼠標(biāo)相對元素的位置 let disX = e.clientX - odiv.offsetLeft; let disY = e.clientY - odiv.offsetTop; let flag = true; document.onmousemove = (e)=>{ //鼠標(biāo)按下并移動的事件 if(flag && x === this.i.length-1){ flag = false; this.i.push({input:''}) } //用鼠標(biāo)的位置減去鼠標(biāo)相對元素的位置,得到元素的位置 let left = e.clientX - disX; let top = e.clientY - disY; //綁定元素位置到positionX和positionY上面 this.positionX = top; this.positionY = left; //移動當(dāng)前元素 odiv.style.left = left + 'px'; odiv.style.top = top + 'px'; }; document.onmouseup = (e) => { document.onmousemove = null; document.onmouseup = null; }; } } } </script> <style scoped lang="less"> .view{ position: absolute; top: 0; bottom: 0; left: 0; right: 0; background: #f8f8f8; .x{ width: 250px; height: 50px; top: 50px; left: 10px; position: absolute; background: red; color: yellow; } } </style>
一個簡單的demo,后續(xù)用的話可以再豐富,比如以拖動長度來觸發(fā)事件。
input可以換成子組件。這里提供分享一個底層的實現(xiàn)方式
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。
當(dāng)前文章:vue模塊拖拽實現(xiàn)示例代碼
文章來源:http://aaarwkj.com/article30/ihpiso.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供電子商務(wù)、全網(wǎng)營銷推廣、響應(yīng)式網(wǎng)站、網(wǎng)站內(nèi)鏈、品牌網(wǎng)站建設(shè)、網(wǎng)站建設(shè)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)