<!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>
拖拽添加心愿
最新推荐文章于 2023-12-29 11:08:35 发布