vue實現拖拽小圖標
如何給vue項目裡面寫拖拽懸浮小圖標呢,供大傢參考,具體內容如下
首先
1、html文件 一定要給父盒子一個ID
<div class="xuanfu" id="moveDiv" @mousedown="down()" @touchstart="down()" @mousemove.prevent.stop="move()" @touchmove.prevent.stop="move()" @mouseup="end()" @touchend="end()" > <img class="img-kf" src="../../assets/images/csVip/kf.png" /> </div>
2、在data裡面設置
position: { x: 0, y: 0 }, nx: "", ny: "", dx: "", dy: "", xPum: "", yPum: "",
3、在方法裡面寫拖拽方法
//移動端拖拽事件 down() { this.flags = true; let touch; if (event.touches) { touch = event.touches[0]; } else { touch = event; } this.position.x = touch.clientX; this.position.y = touch.clientY; this.dx = moveDiv.offsetLeft; this.dy = moveDiv.offsetTop; }, move() { if (this.flags) { let touch; if (event.touches) { touch = event.touches[0]; } else { touch = event; } this.nx = touch.clientX - this.position.x; this.ny = touch.clientY - this.position.y; this.xPum = this.dx + this.nx; this.yPum = this.dy + this.ny; //添加限制:隻允許在屏幕內拖動 //屏幕寬度減去懸浮框寬高 const maxWidth = document.body.clientWidth - 54; const maxHeight = document.body.clientHeight - 54; if (this.xPum < 0) { //屏幕x限制 this.xPum = 0; } else if (this.xPum > maxWidth) { this.xPum = maxWidth; } if (this.yPum < 0) { //屏幕y限制 this.yPum = 0; } else if (this.yPum > maxHeight) { this.yPum = maxHeight; } moveDiv.style.left = this.xPum + "px"; moveDiv.style.top = this.yPum + "px"; //阻止頁面的滑動默認事件 document.addEventListener( "touchmove", function () { // 1.2 如果碰到滑動問題,請註意是否獲取到 touchmove // event.preventDefault(); //jq 阻止冒泡事件 event.stopPropagation(); // 如果沒有引入jq 就用 stopPropagation() }, false ); } }, //鼠標釋放時候的函數 end() { this.flags = false; },
4、css樣式
.xuanfu { width: 1.7rem; height: 1.7rem; border-radius: 50%; // background: rgb(213, 91, 91); position: fixed; bottom: 4rem; right: 0.4rem; z-index: 9999999999; text-align: center; .img-kf { width: 1.7rem; height: 1.7rem; } }
到這裡,我們的懸浮小圖標就做完瞭。
以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。