【问题标题】:jQuery MouseMovejQuery 鼠标移动
【发布时间】:2012-12-14 01:45:56
【问题描述】:

我想要一个图像,当鼠标移动到它的左侧和右侧时,它会变成三个图像。

  • 当光标在左侧时,向左显示左箭头
  • 当光标在中心时,居中显示向上箭头
  • 当光标在右侧时向右显示右箭头

我找到了一个运行良好的 jQuery 脚本。我对其进行了一些编辑,并让它在鼠标移动时显示左右箭头。我只剩下中间部分要做,不知道如何添加。

这就是我所拥有的。 (另见 jsFiddle 页面:http://jsfiddle.net/WhkJB/)

var image_src = {
    left: "http://i.imgur.com/ubKrq.jpg",
    right: "http://i.imgur.com/SxHCS.jpg",
};

$(document).mousemove(function(event){
    var mloc = {
        x: event.pageX,
        y: event.pageY
    };

    if( 
        (mloc.x >= 0 && mloc.x <= $(document).width()/2 )
    ){
        $(".arrow").attr("src", image_src.left);
    }else if( 
        (mloc.x >= $(document).width()/2 && mloc.x <= $(document).width()) &&
        (mloc.y >= 0 && mloc.y <= $(document).height()/2)
    ){
        $(".arrow").attr("src", image_src.right);
    }

});​

另一个问题 - 当您将鼠标移到图像下方时,它不起作用。有没有办法让它在整个页面上移动?

任何帮助将不胜感激。

【问题讨论】:

  • 为什么将x 和y 放在mloc 对象中?无论如何它都是本地的。

标签: jquery mousemove


【解决方案1】:

您可以先计算 X 位置百分比,然后对其应用简单的if。

即:

var image_src = {
    left: "http://i.imgur.com/ubKrq.jpg",
    right: "http://i.imgur.com/SxHCS.jpg",
    up: "http://i.imgur.com/SxHCS.jpg" // replace with UP image
};

$(document).mousemove(function(event){
    var xPercent = (event.pageX / $(document).width()) * 100;
    if(xPercent <= 40) { // show left
        $(".arrow").attr("src", image_src.left);
    }
    else if(xPercent >= 60) { // show right
        $(".arrow").attr("src", image_src.right);
    }
    else { // show up
        $(".arrow").attr("src", image_src.up);
    }
});​​​

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-04
    • 1970-01-01
    • 1970-01-01
    • 2013-09-07
    • 2011-10-16
    • 2018-02-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多