jQuery get mouse position within an element

后端 未结 8 818
日久生厌
日久生厌 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:36

    One way is to use the jQuery offset method to translate the event.pageX and event.pageY coordinates from the event into a mouse position relative to the parent. Here's an example for future reference:

    $("#something").click(function(e){
       var parentOffset = $(this).parent().offset(); 
       //or $(this).offset(); if you really just want the current element's offset
       var relX = e.pageX - parentOffset.left;
       var relY = e.pageY - parentOffset.top;
    });
    
    0 讨论(0)
  • 2020-11-22 17:36

    This solution supports all major browsers including IE. It also takes care of scrolling. First, it retrieves the position of the element relative to the page efficiently, and without using a recursive function. Then it gets the x and y of the mouse click relative to the page and does the subtraction to get the answer which is the position relative to the element (the element can be an image or div for example):

    function getXY(evt) {
        var element = document.getElementById('elementId');  //replace elementId with your element's Id.
        var rect = element.getBoundingClientRect();
        var scrollTop = document.documentElement.scrollTop?
                        document.documentElement.scrollTop:document.body.scrollTop;
        var scrollLeft = document.documentElement.scrollLeft?                   
                        document.documentElement.scrollLeft:document.body.scrollLeft;
        var elementLeft = rect.left+scrollLeft;  
        var elementTop = rect.top+scrollTop;
    
            if (document.all){ //detects using IE   
                x = event.clientX+scrollLeft-elementLeft; //event not evt because of IE
                y = event.clientY+scrollTop-elementTop;
            }
            else{
                x = evt.pageX-elementLeft;
                y = evt.pageY-elementTop;
        }
    
    0 讨论(0)
  • 2020-11-22 17:40

    If you make your parent element be "position: relative", then it will be the "offset parent" for the stuff you're tracking mouse events over. Thus the jQuery "position()" will be relative to that.

    0 讨论(0)
  • 2020-11-22 17:40

    I would suggest this:

    e.pageX - this.getBoundingClientRect().left
    
    0 讨论(0)
  • 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 = $('<div class="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;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="box">
      <p>Hotspot position is at: <span></span></p>
    </div>

    0 讨论(0)
  • 2020-11-22 17:45

    I use this piece of code, its quite nice :)

        <script language="javascript" src="http://code.jquery.com/jquery-1.4.1.js" type="text/javascript"></script>
    <script language="javascript">
    $(document).ready(function(){
        $(".div_container").mousemove(function(e){
            var parentOffset = $(this).parent().offset();
            var relativeXPosition = (e.pageX - parentOffset.left); //offset -> method allows you to retrieve the current position of an element 'relative' to the document
            var relativeYPosition = (e.pageY - parentOffset.top);
            $("#header2").html("<p><strong>X-Position: </strong>"+relativeXPosition+" | <strong>Y-Position: </strong>"+relativeYPosition+"</p>")
        }).mouseout(function(){
            $("#header2").html("<p><strong>X-Position: </strong>"+relativeXPosition+" | <strong>Y-Position: </strong>"+relativeYPosition+"</p>")
        });
    });
    </script>
    
    0 讨论(0)
提交回复
热议问题