jQuery mousemove方向,获得正确的距离

时间:2012-12-28 15:28:10

标签: jquery mousemove direction jquery-hover jquery-calculation

如何,我需要创建一个方向感知悬停效果,但坚持正确的计算。 (这是计算问题还是错误的标记?)

目前为止what I've done

左箭头和右箭头按预期工作,但上下失败。我有什么想法吗?

$("#circle").on('mousemove', function(e) {
    var elem = $(this),
        arrowT = $('.arrow.top'),
        arrowR = $('.arrow.right'),
        arrowB = $('.arrow.bottom'),
        arrowL = $('.arrow.left'),

        offset = elem.offset(),
        pageX = e.pageX - offset.left,
        pageY = e.pageY - offset.top,
        side = {
            top: pageY < (elem.height() / 2),
            left: pageX < (elem.width() / 2),
            bottom: pageY > (elem.height() / 2),
            right: pageX > (elem.width() / 2)
        };


    arrowT.css({
        top: side.top ? pageY - arrowT.outerHeight() : null
    });
    arrowR.css({
        right: side.right ? -(pageX - (elem.width() - arrowR.outerWidth())) : null
    });
    arrowB.css({
        bottom: side.bottom ? -(pageY - (elem.height() - arrowB.outerHeight())) : null
    });
    arrowL.css({
        left: side.left ? pageX - arrowL.outerWidth() : null
    });
});

3 个答案:

答案 0 :(得分:1)

与元素移动时身高变化有关。坚持使用它的大小不变的包装,它们可以工作

http://jsfiddle.net/t4EME/4/

#wrap
{
    height:1000px; overflow:hidden;
    padding-top:100px;
}


<div id="wrap">
    <div id="circle">
        <a href="#" class="arrow top"></a>
        <a href="#" class="arrow right"></a>
        <a href="#" class="arrow bottom"></a>
        <a href="#" class="arrow left"></a>
    </div>
</div>​

答案 1 :(得分:1)

我希望这会有所帮助。那是因为将鼠标移到它上面时元素大小会发生变化。

http://jsfiddle.net/t4EME/5/

topc = $('#circle').position().top;
widk = $('#circle').height();
$("#circle").mousemove( function(e) {
    var elem = $(this),
        arrowT = $('.arrow.top'),
        arrowR = $('.arrow.right'),
        arrowB = $('.arrow.bottom'),
        arrowL = $('.arrow.left'),

        offset = elem.offset(),
        pageX = e.pageX - offset.left,
        pageY = e.pageY - offset.top,
        side = {
            top: pageY < (elem.height() / 2),
            left: pageX < (elem.width() / 2),
            bottom: pageY > (elem.height() / 2),
            right: pageX > (elem.width() / 2)
        };   
if(e.pageY>topc && e.pageY<topc+widk) {
$('.top').css({
    top: side.top ? pageY - arrowT.outerHeight()  : null
});
$('.right').css({
    right: side.right ? -(pageX - (elem.outerWidth() - arrowR.outerWidth())) : null
});
$('.bottom').css({
    bottom: side.bottom ? -(pageY - (elem.outerHeight() - arrowB.outerHeight())) : null
});
$('.left').css({
    left: side.left ? pageX - arrowL.outerWidth() : null
});
}
});​

答案 2 :(得分:0)

http://jsfiddle.net/t4EME/7/

这是一个带链接的工作版本

        top: pageY < (elem.height() / 2) && pageY  > 0 ,
        left: pageX < (elem.width() / 2) && pageX  > 0,
        bottom: pageY > (elem.height() / 2)  && pageY  < elem.height(),
        right: pageX > (elem.width() / 2) && pageX  < elem.width()

由于保证金隐藏了链接

,因此更改为绝对定位
相关问题