简体   繁体   中英

Offset Div background on page load

I currently have a div with a background that is offset -500px x -200px, and reacts with mouse movement. The way I have it set up, it only offsets after the mouse is moved. I have tried several times to get .onload to work so it would offset it as soon at the page loaded, but I'm new to javascript and Jquery and I'm stumped.

Code to move the background of the div:

$(document).ready(function(e){  
    $('.landing-content').mousemove(function(e){
       var x = -(e.pageX + this.offsetLeft) / 80;
       var x2 = x * -1 - 500;
       var y = -(e.pageY + this.offsetTop) / 80;
       var y2 = y * -1 - 200;
       $(this).css('background-position', x2 + 'px ' + y2 + 'px');
    });    
});

Live example: http://afrohorse.netau.net/

If you move your mouse around the screen, then press refresh, you'll see what I mean.

Any help is appreciated, thanks in advance! :)

When your page is loaded, your background position will be what you have set it to in CSS (0, 0 by default, or -500px -200px if you have that set).

Now once a user starts moving his mouse around on your page, you execute the following code:

$('.landing-content').mousemove(function(e){
   var x = -(e.pageX + this.offsetLeft) / 80;
   var x2 = x * -1 - 500;
   var y = -(e.pageY + this.offsetTop) / 80;
   var y2 = y * -1 - 200;
   $(this).css('background-position', x2 + 'px ' + y2 + 'px');
});    

Seeing as how you calculate the offset, it seems pretty logical that you can see it jump when it first initialises. For example, if your CSS sets the offset to -500px -200px, on mousemove jQ will suddenly set it at -580px -256px (depending on where your mouse is located).

You'll need to find a way for JQ to set the background position on pageload, so that it perfectly matches whatever outcome your mousemove calculation will give it once a user starts moving his cursor around.

Fixed it by removing the "- 500" and the "- 200" from the JQ and then adding

margin-left: -500px;
margin-top: -200px;

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