简体   繁体   English

相对于背景当前位置的视差

[英]Parallax relative to a background's current position

I'm attempting to create a parallax effect (which works great) however there is a small problem. 我正在尝试创建视差效果(效果很好),但是存在一个小问题。 Instead of the parallax being relative from the element's current position, it jumps to 0. How would I be able to have the parallax affect it's position relative to it's current position? 视差不是从元素的当前位置开始是相对的,而是跳到0。如何使视差影响它相对于当前位置的位置?

Here is my javascript: 这是我的JavaScript:

$("#caveConfron").mousemove(function(e){
    var x = e.pageX - this.offsetLeft;

    var alreadyY = $("#caveConfron").css("backgroundPositionY");

    $("#caveConfron").css({"backgroundPosition":-(x/85)+"% 0%"});
});

And my CSS for the element: 而我的CSS元素:

#caveConfron{
    width:242px;
    height:344px;
    border:5px solid black;
    background:url('../img/caveConfrontBg.jpg') no-repeat center top;
    position:relative;
}

Here is an example of what happens: http://jsfiddle.net/gNCjS/ 这是发生的情况的示例: http : //jsfiddle.net/gNCjS/

After much experimentation, I figured out the problem. 经过大量实验,我发现了问题所在。

First and foremost, when the mouse hits the center of the div, the value of the mouse position of x should be "0". 首先,当鼠标击中div的中心时,x的鼠标位置值应为“ 0”。 So this is what I did without tweaking the CSS: 所以这是我在不调整CSS的情况下所做的:

$("#caveConfron").mousemove(function(e){
    var x = e.pageX - this.offsetLeft;

    var reduce = $(this).width()/2;

    $("#caveConfron").css({"backgroundPosition":(((-x+reduce)/55)+50)+"% 0%"});
});

The variable reduce gets half of the width of the div. 变量reduce div宽度的一半。 Then, I get the negative of the variable x while adding it to the the value of reduce so if the mouse position of x surpasses half of the div, it will go positive, so the middle will perpetually be "0." 然后,在将变量x加到reduce的值上时得到负数,因此,如果x的鼠标位置超过div的一半,它将变为正数,因此中间值将永远为“ 0”。 I then divide 55 so it wont jump sporadically when moving around on the x axis, it will be a small change (feel free to tweak this value if you want the jump to be much more substantial; for my purposes it was great). 然后我将55除以使它在x轴上移动时不会偶发地跳动,这将是一个很小的变化(如果您希望跳动更大得多,可以随意调整此值;就我的目的而言,这很好。) On top of that, I add 50, because in my original CSS the background's position is centered which coincidentally puts the value (in number terms) at 50%. 最重要的是,我添加了50,因为在我的原始CSS中背景的位置居中,这恰好使值(以数字表示)为50%。

Hope my explanation was good! 希望我的解释很好!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM