简体   繁体   English

根据鼠标指针更改div的位置

[英]Change position of div based on mouse pointer

I am trying to position a div based on mouse position, I managed to get it to work 50%. 我试图根据鼠标位置定位div,我设法使其工作50%。 The problem is that DIV always seems to be much lower than the actual mouse position, I try to minus the offset, no luck. 问题是DIV总是总是比鼠标的实际位置低很多,我尝试减去偏移量,没有运气。

Basically what I want is to float the div(the NEXT link in jsfiddle) vertically, but the DIV should not be able to go outside of the container it is in(the div that has the image in the jsfiddle) 基本上我想要的是将div(jsfiddle中的NEXT链接)垂直浮动,但DIV应该不能移出其所在的容器(在jsfiddle中具有图像的div)

here is the jsfiddle: http://jsfiddle.net/LYmVH/7/ 这是jsfiddle: http : //jsfiddle.net/LYmVH/7/

below is the JS, which is also in the jsfiddle: 下面是JS,它也在jsfiddle中:

$('.post-single-content').mousemove(function(e){
    var height=e.pageY,
        height1 =$('.content-top').height(); 
    $('.btnNext').css({top: (e.pageY + 50) + "px"});
});

You need measure against the top of the parent element since it's absolutely positioned in it. 您需要在父元素的顶部进行度量,因为它绝对位于其中。

Try changing your JS to: 尝试将您的JS更改为:

$('.post-single-content').mousemove(function(e){
    var top = (e.pageY - $(this).offset().top) + 'px';
    $('.btnNext').css({ top: top });
});

Upon reading some comments lemme update, by making use some basic math and create "collision". 在阅读了一些评论后,我通过使用一些基本数学知识并创建“碰撞”来更新lemme。 Somthing like: 有点像:

$('.post-single-content').mousemove(function(e){
    var y = e.pageY,  //  mouse y axis position
        tHeight = $(this).height(),  //  container height
        bHeight = $('.btnNext').height(),  //  button height
        oTop = $(this).offset().top,  //  offset top position of container
        abBot = tHeight - $('.btnNext').height(),  //  absolute top of button when at bottom
        bHalf = bHeight / 2,  //  half button height
        top = y - oTop - bHalf,  //  initial top pos of button
        bot = y - oTop + bHalf;  //  bottom of button while moving

    if (top < 0) top = 0;  //  ensure button doesn't go to far north
    else if (bot > tHeight) top = abBot;  //  ensure it cant go past south

    $('.btnNext').css({ top: top });  //  'px' not neccesary
});

jsFiddle 的jsfiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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