jQuery Mousemove 视差效果移动 div 的位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30761409/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:44:10  来源:igfitidea点击:

Mousemove parallax effect moves position of div

jquerycssparallax

提问by Francesca

I'm trying to create a slight parallax effect (I'm not sure if it really constitutes parallax but it's a similar idea). Where there are four layers which all move around at a slightly different rate when the mouse moves.

我正在尝试创建一个轻微的视差效果(我不确定它是否真的构成视差,但这是一个类似的想法)。当鼠标移动时,有四层都以略有不同的速度移动。

I have found a great example that offers something similar to what I want:

我找到了一个很好的例子,它提供了类似于我想要的东西:

http://jsfiddle.net/X7UwG/2/

http://jsfiddle.net/X7UwG/2/

It achieves this by shifting the background position on the #landing-contentdiv when the mouse moves.

它通过#landing-content在鼠标移动时移动 div上的背景位置来实现这一点。

$(document).ready(function(){
  $('#landing-content').mousemove(function(e){
    var x = -(e.pageX + this.offsetLeft) / 20;
    var y = -(e.pageY + this.offsetTop) / 20;
    $(this).css('background-position', x + 'px ' + y + 'px');
  });  
});

However, I cannot work out a way to get this to work not on a background-positionshift, but on a divposition shift. E.g position:relative;and top:xso that the div itself moves around a little.

但是,我无法找到一种方法来让它在background-position轮班上而不是在div位置转移时起作用。例如position:relative;top:x这样 div 本身就会移动一点。

My reasoning is that the div contains CSS animation elements so it needs to be a div with content inside it, not a background image.

我的理由是 div 包含 CSS 动画元素,因此它需要是一个包含内容的 div,而不是背景图像。

Any solutions for this using the code above?

使用上面的代码对此有任何解决方案吗?

回答by Josh Bilderback

How about using jQuery.offSet() instead? You might want to adjust the math/values, but I think it should set you in the right direction.

改用 jQuery.offSet() 怎么样?您可能想要调整数学/值,但我认为它应该让您朝着正确的方向前进。

$(document).ready(function () {
    $('#layer-one').mousemove(function (e) {
        parallax(e, this, 1);
        parallax(e, document.getElementById('layer-two'), 2);
        parallax(e, document.getElementById('layer-three'), 3);
    });
});

function parallax(e, target, layer) {
    var layer_coeff = 10 / layer;
    var x = ($(window).width() - target.offsetWidth) / 2 - (e.pageX - ($(window).width() / 2)) / layer_coeff;
    var y = ($(window).height() - target.offsetHeight) / 2 - (e.pageY - ($(window).height() / 2)) / layer_coeff;
    $(target).offset({ top: y ,left : x });
};

JSFiddle: http://jsfiddle.net/X7UwG/854/

JSFiddle:http: //jsfiddle.net/X7UwG/854/