简体   繁体   中英

how can i measure cursor position in a div..?

i don't know what should be the question title..sorry for this. but i explain that what i want to do. i have a div with class name "scroll-inner-container" this div height is 70vh. when my mouse hover into this div from top to 10% (this is the mouse hover area 0% to 10% in this div) and bottom to 10% then a function will start.

How can I measure this area into this div by using js...?

My html code looks like:

<div class="scroll-inner-container">
  <div class="paragraph-space content">
    <h1>top position</h1>           
      <p>Lorem ipsum dolor...</p>
    <h1>end position</h1>
</div>

my css code here for this div:

.scroll-inner-container{
height: -moz-calc(70vh + 0px);
height: -webkit-calc(70vh + 0px);
height: calc(70vh + 0px);
overflow: auto;
object-fit: cover;
background-color: yellow;
position: relative;
}

I've previously used code similar to this for a project, copied from a previous question How to get mouse position - relative to element

var x,y;
$("#div1").mousemove(function(event) {
    var offset = $(this).offset();
    x = event.pageX- offset.left;
    y = event.pageY- offset.top;
    $("#div1").html("(X: "+x+", Y: "+y+")");
});

Once the mouse goes past a specified point on the Y axis, you can execute your code.

I think this code segment will help you. It will check the mouse position with your parent container, You can call your function inside the if condition.

var obj = $('.scroll-inner-container');
var top, left, bottom, right;
var excldH,objHeight,objWidth;
getPos(obj)

//Calls fuction on mouse over
obj.mousemove(function(e) {
    handleMouseMove(e)
});

//Get position of mouse pointer
function handleMouseMove(e) {
    var posX = e.clientX;
    var posY = e.clientY;
    if(posY > top+excldH && posY < bottom - excldH){
        //Here your stuffs go
        console.log(posX)
        console.log(posY)
    }
}

// Get position of the div 'scroll-inner-container'
function getPos(obj) {
    var offsets = obj.offset();
    objHeight = obj.height();
    objWidth = obj.width();
    excldH = objHeight/10; //Caculating 10% height
    top = offsets.top,
    // left = offsets.left,
    bottom = top+objHeight,
    // right = left+objWidth
}

Here is a jsfiddle for that

I tried to add here as snippet, but didn't worked. You can inspect the result on console.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM