Mousemove视差效果可移动div的位置 [英] Mousemove parallax effect moves position of div
问题描述
我正在尝试创建轻微的视差效果(我不确定它是否真的构成视差,但这是一个相似的想法).当鼠标移动时,共有四层,它们的移动速度略有不同.
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:
它通过在鼠标移动时移动#landing-content
div上的背景位置来实现.
It achieves this by shifting the background position on the #landing-content
div when the mouse moves.
$(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');
});
});
但是,我无法找到一种方法来使它不能在background-position
位置上移动,而在div
位置上移动.例如position:relative;
和top:x
,以便div本身稍微移动一下.
However, I cannot work out a way to get this to work not on a background-position
shift, but on a div
position shift. E.g position:relative;
and top:x
so that the div itself moves around a little.
我的理由是div包含CSS动画元素,因此它必须是一个内部包含内容的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.
是否有使用上述代码的解决方案?
推荐答案
如何改用jQuery.offSet()?您可能想要调整数学/值,但我认为它应该为您设定正确的方向.
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.
$(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/
这篇关于Mousemove视差效果可移动div的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!