溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

教你使用vue寫一個拖拽功能

發(fā)布時間:2020-11-04 16:02:19 來源:億速云 閱讀:273 作者:Leah 欄目:開發(fā)技術

教你使用vue寫一個拖拽功能?相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。

效果圖

教你使用vue寫一個拖拽功能

實現步驟html

總結了一下評論,好像發(fā)現大家都碰到了滑動的問題。就在這里提醒一下吧??蓪⒃搼腋?DIV 同你的 scroller web 同級。

<template>
	<div id="webId">
  	<div>你的web頁面</div>
	  <!-- 1.1 如果碰到滑動問題,請檢查這里是否屬于同一點。 -->
	  <!-- 懸浮的HTML -->
	  <div class="xuanfu" id="moveDiv"
	   @mousedown="down()" @touchstart="down()"
	   @mousemove.prevent.stop="move()"
     @touchmove.prevent.stop="move()"
	   @mouseup="end()" @touchend="end()"
	  >
	   <div class="yuanqiu">11</div>
	  </div>
	</div>
</template>

js

<script>
data() {
 return {
  flags: false,
  position: { x: 0, y: 0 },
  nx: '', ny: '', dx: '', dy: '', xPum: '', yPum: '',
 }
}

methods: {
 // 實現移動端拖拽
 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;
 },
}
</script>

css

<style>
 /*css樣式可自定義 僅提供參考*/
 #webId { position: relative; }
 .xuanfu {
  height: 54px; /* rem = 12px */
  width: 54px;
  /*1.3 如果碰到滑動問題,請檢查 z-index。z-index需比web大一級*/
  z-index: 999;
  position: fixed;
  top: 4.2rem;
  right: 3.2rem;
  border-radius: 0.8rem;
  background-color: rgba(0, 0, 0, 0.55);
 }
 .yuanqiu {
  height: 2.7rem;
  width: 2.7rem;
  border: 0.3rem solid rgba(140, 136, 136, 0.5);
  margin: 0.65rem auto;
  color: #000000;
  font-size: 1.6rem;
  line-height: 2.7rem;
  text-align: center;
  border-radius: 100%;
  background-color: #ffffff;
 }
</style>

看完上述內容,你們掌握教你使用vue寫一個拖拽功能的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI