效果如上图(有点简陋),原理就是先给图片添加draggable="false"禁止默认拖动事件,获取眼睛图片对象添加addEventListener,通过公式(移动后鼠标点击位置距离左边的长度 - (移动前鼠标点击位置距离左边的长度-移动前眼睛图片距离左边的长度)求得移动后眼睛图片距离左边的长度,通过定位设置眼睛最终的位置,高度同理,然后document.removeEventListener去掉事件监听,再根据事先测量好的位置来判断是否正确(移动端同理,把鼠标mouse事件换成touch相关事件即可)
代码
<template>
<div class="hello">
<h1 v-text="tip" style="text-align: left;color: pink" id="tip"></h1>
<div class="content">
<img src="./total.jpg" alt="" class="total" ref="total" draggable="false">
<img src="./eye.jpg" alt="" class="eye" ref="eye" draggable="false">
</div>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data(){
return{
tip:'请拖动眼睛到指定位置'
}
},
mounted(){
this.$nextTick(()=>{
let eye = document.querySelector('.eye')
let content = document.querySelector('.content')
let tip = document.getElementById('tip')
let photoleft = content.offsetLeft
let phototop = content.offsetTop
let that = this
eye.addEventListener('mousedown',(e)=>{
let eyeLeft = e.pageX - photoleft - eye.offsetLeft
let eyeTop = e.pageY - phototop - eye.offsetTop
function moving(e){
eye.style.left = e.pageX - eyeLeft - photoleft + 'px'
eye.style.top = e.pageY - eyeTop - phototop + 'px'
}
document.addEventListener('mousemove',moving,false)
document.addEventListener('mouseup',(e)=> {
let left = e.pageX - eyeLeft - photoleft
let top = e.pageY - eyeTop - phototop
if(left>330&&left<340&&top>255&&top<263){
that.tip = '验证成功'
tip.style.color = '#00aaee'
}else{
that.tip = '验证失败'
tip.style.color = 'red'
setTimeout(()=>{
eye.style.left = '0px'
eye.style.top = '0px'
},1000)
}
document.removeEventListener('mousemove', moving)
},false)
},false)
})
},
methods:{
}
}
</script>
<style scoped>
*{
margin:0;
padding:0
}
.content{
position: relative;
}
.total{
position: absolute;
top: 0;
left: 0;
}
.eye{
position: absolute;
top: 0;
left: 0;
}
</style>