Home  >  Q&A  >  body text

javascript - How to implement the distance between the inside of a DIV and the mouse in JS

This is a problem that I can’t solve even if I tear my brain apart↓

Front-ends! As shown in the figure, how to obtain the coordinate distance from the leftmost side of p to the mouse position?

大家讲道理大家讲道理2713 days ago546

reply all(2)I'll reply

  • PHP中文网

    PHP中文网2017-05-16 13:39:29

        body{
            margin:0;
            padding:0;
        }
        #p{
            width:200px;
            height:100px;
            border:1px solid #000;
            position:absolute;
        }
        //如果p有定位父级元素存在还需要减去offsetTop值
        $("#p").bind("click",function(ev){
            console.log(ev.clientX - $(this).offset().left);
        })

    reply
    0
  • 仅有的幸福

    仅有的幸福2017-05-16 13:39:29

    $("p").on("click",function(e){
        var disX = e.clientX - e.offsetX;    //disX就是当前p最左侧到鼠标位置的坐标距离
    });

    reply
    0
  • Cancelreply