鼠標跟隨相信大家都很熟悉了,在這里我的隨筆呢說的是怎么在vue中使用鼠標跟隨,onmousedown,onmousemove 這些事件是原生事件,按理說vue使用是沒有問題的,況且pc大部分事件是可以在移動端使用的,但是在vue項目中使用它卻不生效,沒有效果。
然后百度查詢vue事件,了解到vue已經規定了移動端wap使用的事件,touchstart,touchmove等,這樣往下開展工作就容易多了!直接上實例吧
樣式:
#box {
width: 100px;
height: 100px;
// aquamarine;
position: fixed;
top: 200px;
right: 30px;
z-index: 999;
-webkit-app-region: no-drag;
}
img {
width: 100%;
height: 100%;
cursor: move;
}
#scale {
width: 10px;
height: 10px;
overflow: hidden;
cursor: se-resize;
position: absolute;
right: 0;
bottom: 0;
// background-color: rgb(122,191,238);
}
結構:
<div id="father">
<div id="box">
<img src="http://d.hiphotos.baidu.com/zhidao/pic/item/e61190ef76c6a7efd517f640fbfaaf51f3de66a6.jpg"/>
<div id="scale"></div>
</div>
</div>
methods:
mouseFollow (that) {
// box是裝圖片的容器,fa是圖片移動縮放的范圍,scale是控制縮放的小圖標
var box = document.getElementById('box')
var fa = document.getElementById('father')
// var scale = document.getElementById('scale')
// 圖片移動效果
box.addEventListener('touchstart', function (ev) {
document.getElementById('box').setAttribute('data-flag', false)
var firstTime = new Date().getTime()
var oEvent = ev
// 瀏覽器有一些圖片的默認事件,這里要阻止
oEvent.preventDefault()
var disX = oEvent.touches[0].clientX - box.offsetLeft
var disY = oEvent.touches[0].clientY - box.offsetTop
fa.addEventListener('touchmove', function (ev) {
oEvent = ev
oEvent.preventDefault()
var x = oEvent.touches[0].clientX - disX
var y = oEvent.touches[0].clientY - disY
// 圖形移動的邊界判斷
x = x <= 0 ? 0 : x
x =
x >= fa.offsetWidth - box.offsetWidth
? fa.offsetWidth - box.offsetWidth
: x
y = y <= 95 ? 95 : y
y =
y >=
(document.documentElement.clientHeight ||
document.body.clientHeight) -
(box.clientHeight + 10)
? (document.documentElement.clientHeight ||
document.body.clientHeight) -
(box.clientHeight + 10)
: y
// 圖片的新定位
box.style.left = x + 'px'
box.style.top = y + 'px'
})
// 圖形移出父盒子取消移動事件,防止移動過快觸發鼠標移出事件,導致鼠標彈起事件失效
fa.onmouseleave = function () {
fa.addEventListener('touchmove', null)
fa.onmouseup = null
}
// 鼠標彈起后停止移動
fa.addEventListener('touchend', function () {
var lastTime = new Date().getTime()
if ((lastTime - firstTime) < 200) {
that.$router.push({path: '/drugstore/addcar'})
document.getElementById('box').setAttribute('data-flag', true)
return false
}
fa.addEventListener('touchmove', null)
fa.onmouseup = null
})
})
}
mounted:
var that = this
this.mouseFollow(that)