简体   繁体   中英

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?

Here is my 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:

#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/

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". So this is what I did without tweaking the 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. 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." 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). 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%.

Hope my explanation was good!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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