1. 程式人生 > 其它 >拖拽新增心願

拖拽新增心願

技術標籤:vue

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge"
> <title>Document</title> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <style> ul{ list-style: none; display: flex; width: 300px; justify-content: space-around; } ul>
li{ width: 50px; height: 50px; border-radius: 50%; } .ac{ border: 3px solid yellow; } .box{ position: absolute; width: 100px; height: 100px; } </style> </head> <body>
<div id="app"> <div> <input type="text" v-model="text"> </div> <div> <ul> <li v-for="(item,index) in msg" :style="item" :class="num==index?'ac':''" @click="add(index)"></li> </ul> </div> <button @click="sure">確認</button> <!-- 新增的<div></div> --> <div class="box" v-for="(item,index) in arr" :style='{background:item.bg,left:item.left,top:item.top}' v-drag="item" >{{ item.text }}</div> </div> </body> <script> let vm=new Vue({ el:"#app", data(){ return { text:"", msg:[ {background:"red",done:false}, {background:"blue",done:false}, {background:"pink",done:false}, {background:"black",done:false} ], num:-1, str:{ }, arr:[] } }, methods:{ //點選選中對應的某一項 add(index){ this.num=index this.msg[index].done=true }, sure(){ //獲取輸入值 let left=parseInt(Math.random()*600)+"px" let top=parseInt(Math.random()*600)+"px" console.log(left,top) //通過every方法來辨別使用者是否選擇了背景 let a=this.msg.every((v,i)=>{ return v.done==false }) console.log(a) if(a||this.text==""){ alert("必須新增心願和選擇背景") return }else{ this.str={text:this.text,bg:this.msg[this.num].background,left,top} this.arr.push(this.str) } } }, directives:{ drag:(el,binding)=>{ // console.log(vm) // let index = vm.arr.findIndex((item)=>{ // return item.text == binding.value.text // }) //拖拽 滑鼠按下移動 el.onmousedown = function() { let ev=event let x=ev.clientX let y=ev.clientY let m=el.offsetLeft let n=el.offsetTop document.onmousemove=function(ev){ let x1=ev.clientX let y1=ev.clientY let x2=x1-x+m let y2=y1-y+n binding.value.left=x2 binding.value.top=y2 el.style.left=binding.value.left+"px" el.style.top=binding.value.top+"px" binding.value.left=el.style.left binding.value.top=el.style.top // 拖拽之後改變資料 console.log(vm.arr) // console.log(index) // vm.arr[index].left = el.style.left // vm.arr[index].top = el.style.top // vm.str.left=el.style.left // vm.str.top=el.style.top } //滑鼠抬起停止移動 document.onmouseup = function(event) { document.onmousemove = null; } } } }, //物件和陣列,都需要深度監聽,簡單的字串和布林不用 watch:{ arr:{ handler(){ console.log(123) window.localStorage.setItem("key",JSON.stringify(this.arr)) }, deep:true } }, created(){ let aa=window.localStorage.getItem("key") if(aa){ this.arr=JSON.parse(aa) } } }) </script> </html>