Make Background image move with mouse in Jquery
I found this snippet of code, and tweaked it a bit for my website:
var vH=jQuery('.categoryWrapper').height();
var vW=jQuery('.categoryWrapper').width();
var vT=jQuery('.categoryWrapper').offset().top;
var vL=jQuery('.categoryWrapper').offset().left;
jQuery('.categoryWrapper').mousemove(function(e){
var ypos开发者_运维百科=e.pageY-vT;
var xpos=e.pageX-vL;
var y=Math.round(ypos/vW*100);
var x=Math.round(xpos/vH*100);
jQuery(this).css({backgroundPosition: x+'% '+y+'%'});
However, it's not quite doing what I want it to, and I am having a hard time tweaking this to work right.
Go to http://photoshop.tutorialcraft.com , and move your mouse over the "Photoshop Tutorials, "Graphic Inspiration", and "Graphic Downloads" buttons.
Basically, I have a PNG file with a radial gradient. I want the background to track the mouse, but move a little faster than the mouse.
For instance, .categoryWrapper
is 312 x 88 pixels. The actually background img is 277x277. If I move my mouse in via the top of .categoryWrapper
, the center of the bg IMG should be about 200px above the point where the mouse entered. As you move the mouse to the bottom, the background should move to about 200px below the mouse (that way the bg img appears and disappears when you move in and out).
Below image should illustrate what I am trying to do:
Shouldn't this
var y=Math.round(ypos/vW*100);
var x=Math.round(xpos/vH*100);
be like this
var y=Math.round(ypos/vH*100);
var x=Math.round(xpos/vW*100);
since x is the horizontal ( => width) and y is the vertical ( => height) axis?
I am pretty sure that once you change this it will work as expected.
EDIT:
You should also make sure that vH
, vW
, vT
and vL
are set to the corresponding attributes of the current element, i.e.
//Gradient Effect
jQuery('.categoryWrapper').mousemove(function(e){
var vH=jQuery(this).height();
var vW=jQuery(this).width();
var vT=jQuery(this).offset().top;
var vL=jQuery(this).offset().left;
var ypos=e.pageY-vT;
var xpos=e.pageX-vL;
var y=Math.round(ypos/vH*100);
//var x=Math.round(xpos/vW*100);
var x=Math.round((xpos/vW*100 - 50)*15);
jQuery(this).css({backgroundPosition: x+'% '+y+'%'});
jQuery('#x').text(x);
jQuery('#y').text(y);
By setting them outside the mousemove
handler they take the values based on the whole collection returned by the '.categoryWrapper' selector, and not just the element under the mouse at the moment of mousemove
精彩评论