javascript - 鼠标离开 div 后将图像动画到原始位置

标签 javascript jquery html css

我正在使用的 JS 脚本通过鼠标悬停在一些图像上创建视差效果。鼠标离开悬停区域后,图像将保留在最后一个位置,直到用户重新进入悬停区域 - 这会导致图像捕捉到新的鼠标位置。

我一直在尝试修改脚本以在原点位置启动图像,然后在检测到鼠标悬停时平滑地动画到鼠标位置,离开后再次返回原点。我对任何疯狂的解决方案持开放态度,我也尝试过利用 CSS 动画但无济于事。

JS:

$(document).ready(function ( $ ) {
    $.fn.extend({

        mouseParallax: function(options) {

            var defaults = { moveFactor: 5, zIndexValue: "-1", targetContainer: 'body' };

            var options = $.extend(defaults, options);

            return this.each(function() {
                var o = options;
                var background = $(this);

                $(o.targetContainer).on('mousemove', function(e){

                    mouseX = e.pageX;
                    mouseY = e.pageY;

                    windowWidth = $(window).width();
                    windowHeight = $(window).height();

                    percentX = ((mouseX/windowWidth)*o.moveFactor) - (o.moveFactor/2);
                    percentY = ((mouseY/windowHeight)*o.moveFactor) - (o.moveFactor/2);

                    leftString = (0-percentX-o.moveFactor)+"%";
                    rightString = (0-percentX-o.moveFactor)+"%";
                    topString = (0-percentY-o.moveFactor)+"%";
                    bottomString = (0-percentY-o.moveFactor)+"%";

                    background[0].style.left = leftString;
                    background[0].style.right = rightString;
                    background[0].style.top = topString;
                    background[0].style.bottom = bottomString;
                    if(o.zIndexValue) { 
                        background[0].style.zIndex = o.zIndexValue;
                    }
                });
            });
        }                   
    });

  $('#background').mouseParallax({ moveFactor: 5 });
    $('#foreground').mouseParallax({ moveFactor: 10 });
    $('#fore-foreground').mouseParallax({ moveFactor: 15 });
    $('#fore-fore-foreground').mouseParallax({ moveFactor: 20 });

    $('body').height(3000);

} (jQuery) );

fiddle :https://jsfiddle.net/zj9djopm/2/

最佳答案

与其简单地让它们卡入到位,不如尝试利用 jQuery 为您提供的 .animate 属性。

像这样的东西应该可以工作:

$(o.targetContainer).on('mouseout', function(e){
  $(background[0]).animate({
    left: "0",
    right: "0",
    top: "0",
    bottom: "0"
  });
});

类似地,对于 mouseenter 状态,您必须再次执行相同的操作。

关于javascript - 鼠标离开 div 后将图像动画到原始位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37596574/

相关文章:

jquery 在元素之间包裹内容

javascript - 使用 jQuery 的 Html5 postMessage,但不是 jQuery-postMessage 脚本

javascript - 更改每张幻灯片的容器背景

Javascript 在类中选择下拉选项

javascript - 如何链接一系列返回 promise 并需要不同参数的函数?

javascript - 将两个数组组合成选项数组

javascript - 将表单提交到弹出窗口?

javascript - 空 JavaScript 函数的骨架

html - 使用 css 在文本后添加 '.'(句点)

iphone - iOS 为 HTML5 Canvas 的高度宽度设置了哪些最大值?