jQuery get mouse position within an element

后端 未结 8 983
日久生厌
日久生厌 2020-11-22 16:56

I was hoping to craft a control where a user could click inside a div, then drag the mouse, then let up on the mouse in order to indicate how long they want something to be.

8条回答
  •  礼貌的吻别
    2020-11-22 17:44

    Here is one that also gives you percent position of the point in case you need it. https://jsfiddle.net/Themezly/2etbhw01/

    function ThzhotspotPosition(evt, el, hotspotsize, percent) {
      var left = el.offset().left;
      var top = el.offset().top;
      var hotspot = hotspotsize ? hotspotsize : 0;
      if (percent) {
        x = (evt.pageX - left - (hotspot / 2)) / el.outerWidth() * 100 + '%';
        y = (evt.pageY - top - (hotspot / 2)) / el.outerHeight() * 100 + '%';
      } else {
        x = (evt.pageX - left - (hotspot / 2));
        y = (evt.pageY - top - (hotspot / 2));
      }
    
      return {
        x: x,
        y: y
      };
    }
    
    
    
    $(function() {
    
      $('.box').click(function(e) {
    
        var hp = ThzhotspotPosition(e, $(this), 20, true); // true = percent | false or no attr = px
    
        var hotspot = $('
    ').css({ left: hp.x, top: hp.y, }); $(this).append(hotspot); $("span").text("X: " + hp.x + ", Y: " + hp.y); }); });
    .box {
      width: 400px;
      height: 400px;
      background: #efefef;
      margin: 20px;
      padding: 20px;
      position: relative;
      top: 20px;
      left: 20px;
    }
    
    .hotspot {
      position: absolute;
      left: 0;
      top: 0;
      height: 20px;
      width: 20px;
      background: green;
      border-radius: 20px;
    }
    
    

    Hotspot position is at:

提交回复
热议问题