vue 移动dom元素 至click的位置方法?

        htmlElement = document.getElementById('icon-option-list') as HTMLElement  (是绝对定位 ,不确定 top 与 left 位置)
 
        let x = htmlElement.getBoundingClientRect().top - e.clientY    // 点击位置 与 htmlElement 元素的 x相差距离,这样算对吗?
        let y = htmlElement.getBoundingClientRect().left - e.clientX   // 点击位置 与 htmlElement 元素的  y相差距离
          在不知道 htmlElement 相对 定位元素 的位置时,不
         现在我要把 htmlElement  元素 移动到点击位置, 怎么移动?


        这样好象不对:
            htmlElement.style.top = htmlElement.offsetTop + y +'px'
            htmlElement.style.left = htmlElement.offsetLeft + x+'px'

直接设置htmlElement 的left/top为事件对象e.clientX和e.clientY就可了。e.clientX和e.clientY就是点击的位置,移动到这个位置不需要再计算,不过是居于htmlElement 的左上角,如果htmlElement 的中心点在点击的位置需要计算过


<div id="icon-option-list" style="position:absolute;left:0;top:0;border:solid 1px #ccc;padding:10px">icon-option-list</div>
<script>
    document.onclick = function (e) {
        htmlElement = document.getElementById('icon-option-list')// as HTMLElement

        //居于htmlElement左上角
        //htmlElement.style.left = e.clientX + 'px'
        //htmlElement.style.top = e.clientY + 'px'

        //下面居于htmlElement中心点
        let info = htmlElement.getBoundingClientRect()

        htmlElement.style.left = e.clientX-info.width/2 + 'px'
        htmlElement.style.top = e.clientY - info.height / 2 + 'px'
    }
</script>

  1. 给icon-option-list元素添加个样式:position: absolute;
  2. 鼠标点击后,dom元素的移动代码:
     var x=e.pageX + 'px';
     var y=e.pageY + 'px';
     htmlElement.style.left = x;
     htmlElement.style.top = y;
    

直接获取点击的位置所在的left 和top ,然后把htmlElement 的left 和top 直接赋值就好了
以下是获取点击位置所在的left 和top 的一个函数:

function getPointerPosition(e){
       var obj = e.currentTarget||document.activeElement;
       var position = {
              //clientY ie和firefox都支持,表示鼠标到页面顶的距离,但是不包括滚动条里面的距离
              //pageY firefox支持 表示鼠标到页面顶的距离,包括滚动条里面的距离
              //document.documentElement.scrollTop   firefox支持的 就是滚动条上面的看不到局域的高度
              //document.body.scrollTop   ie支持的  就是滚动条上面的看不到局域的高度
              left:e.pageX || (e.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft)),
              top:e.pageY || (e.clientY + (document.documentElement.scrollTop || document.body.scrollTop))
           };
       return position;
}
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632