鍍金池/ 問答/HTML5  室內(nèi)設(shè)計(jì)  HTML/ js寫一個(gè)拖拽容器的方法,如何相對(duì)父容器移動(dòng)且不被容器內(nèi)其他元素干擾?

js寫一個(gè)拖拽容器的方法,如何相對(duì)父容器移動(dòng)且不被容器內(nèi)其他元素干擾?

如下代碼,坐標(biāo)位置采用event.offsetX,但是移動(dòng)div時(shí)因?yàn)閠oElement時(shí)而指向錯(cuò)誤,導(dǎo)致鼠標(biāo)位置計(jì)算出錯(cuò)。

<svg ref="svg" 
  :width="panelObj.panelWidth" :height="panelObj.panelHeight" 
  @mousedown.stop.prevent="selectStar($event)" @mouseup="selectOver()" 
  @mousemove="moveInPanel($event)" @click.right.prevent="panelRightClick($event)">
  <!-- 繪制節(jié)點(diǎn) -->
  <g v-for="(node,i) in nodes" :key="i">
    <foreignObject :x="node.x" :y="node.y" :width="node.width" :height="node.height">
      <!-- 鼠標(biāo)的toElement時(shí)而指向svg,時(shí)而指向p導(dǎo)致坐標(biāo)位置算錯(cuò) -->
      <div @mousedown.stop.prevent="choseNode($event,node)" @mouseup.stop.prevent="moveOver()">
        <p v-for="(list,i) in node.textList" :key="i">{{list.label}}</p>
      </div>
      <!-- 鼠標(biāo)的toElement指向svg,坐標(biāo)位置正確,但鼠標(biāo)在div范圍內(nèi)移動(dòng)無反應(yīng) -->
      <!-- <div @mousemove.stop @mousedown.stop.prevent="choseNode($event,node)" @mouseup.stop.prevent="moveOver()">
        <p v-for="(list,i) in node.textList" :key="i">{{list.label}}</p>
      </div> -->
      <!-- 鼠標(biāo)的toElement指向svg,坐標(biāo)位置正確,但鼠標(biāo)在p范圍內(nèi)移動(dòng)無反應(yīng) -->
      <!-- <div @mousedown.stop.prevent="choseNode($event,node)" @mouseup.stop.prevent="moveOver()">
        <p @mousemove.stop v-for="(list,i) in node.textList" :key="i">{{list.label}}</p>
      </div> -->
    </foreignObject>
  </g>
</svg>

若采用event.clientX之類的計(jì)算坐標(biāo),不會(huì)出現(xiàn)該問題,但無法考慮出現(xiàn)滾動(dòng)條的情形。

回答
編輯回答
苦妄

你不把JS貼出來還真不知道你要做什么; 看起來是用vue在操作svg什么東西;

對(duì)于拖拽總結(jié)兩點(diǎn)經(jīng)驗(yàn)給你:
mousemove 事件中 event.clientXdom.getBoundingClientRect() 是絕配,基本上不用管父節(jié)點(diǎn)滾動(dòng)條什么的;
offsetX 不是標(biāo)準(zhǔn),而且還和dom掛鉤,不好用;
mousemove 事件最好是動(dòng)態(tài)綁到 document 上,體驗(yàn)會(huì)好些.

2018年5月13日 17:26