[英]Change position of div based on mouse pointer
我試圖根據鼠標位置定位div,我設法使其工作50%。 問題是DIV總是總是比鼠標的實際位置低很多,我嘗試減去偏移量,沒有運氣。
基本上我想要的是將div(jsfiddle中的NEXT鏈接)垂直浮動,但DIV應該不能移出其所在的容器(在jsfiddle中具有圖像的div)
這是jsfiddle: http : //jsfiddle.net/LYmVH/7/
下面是JS,它也在jsfiddle中:
$('.post-single-content').mousemove(function(e){
var height=e.pageY,
height1 =$('.content-top').height();
$('.btnNext').css({top: (e.pageY + 50) + "px"});
});
您需要在父元素的頂部進行度量,因為它絕對位於其中。
嘗試將您的JS更改為:
$('.post-single-content').mousemove(function(e){
var top = (e.pageY - $(this).offset().top) + 'px';
$('.btnNext').css({ top: top });
});
在閱讀了一些評論后,我通過使用一些基本數學知識並創建“碰撞”來更新lemme。 有點像:
$('.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
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.