不知你有没注意到我的网站首页,上面浮动着一层雪花的背景,并且随着鼠标的移动也在移动着。
本文主要讲述了如何判断鼠标的位置,从而实现图片跟随鼠标进行浮动。为了方便查看和理解,在Demo的左下角把各个参数都打印了出来。
CSS CODE:
<style type="text/css">
*{ margin:0; padding:0;}
body{ font-family:Arial; font-size:12px; background:url(bg.png) no-repeat; background-position:center center; background-attachment:fixed;}
input{ width:100px;}
span{ display:inline-block; width:120px;}
#window{ color:white; position:absolute; bottom:10px; left:10px;}
#coordinate{ color:white; position:absolute; bottom:35px; left:10px;}
#location{ color:white; position:absolute; bottom:60px; left:10px;}
#float_bg{ width:2496px; height:1060px; background:url(float_bg.png) no-repeat; position:fixed;}
</style>
HTML CODE:
<div id="float_bg"></div> <div id="window"> <span id="window_x"></span> <span id="window_y"></span> </div> <div id="location"> <span id="location_x"></span> <span id="location_y"></span> </div> <div id="coordinate"> <span id="mouse_x"></span> <span id="mouse_y"></span> </div> <div id="test"> <span id="test_a"></span> <span id="test_b"></span> </div>
JAVASCRIPT CODE:
$(function(){
var my=0,mx=0;
$(document).mousemove(function(e){
var x=e.pageX,y=e.pageY;
if(mx==0) mx=x;
if(my==0) my=y;
ml = x-mx;
ml = Math.ceil(ml/150); //将小数部分一律向整数部分进位。如:Math.ceil(10.0) 返回10 / Math.ceil(10.1) 返回11
$('#float_bg').css('left',ml);
mt = y-my;
mt = Math.ceil(mt/100);
$('#float_bg').css('top',mt);
var doc_width = $(document).width();
var doc_height = $(document).height();
var half_height = doc_width/2;
var half_width = doc_height/2;
$("#window_x").text( "Width: " + doc_width );
$("#window_y").text( "Height: " + doc_height);
$("#mouse_x").text( "Abscissa: " + x );
$("#mouse_y").text( "Ordinate: " + y );
if( half_height > x){ //鼠标的x位置
$("#location_x").text( "Location: Left" );
}else{
$("#location_x").text( "Location: Right" );
}
if( half_width > y){ //鼠标的y位置
$("#location_y").text( "Location: Up" );
}else{
$("#location_y").text( "Location: Down" );
}
});
});
感谢您的阅读,本文由 蓝色梦想 版权所有。如若转载,请注明出处:蓝色梦想 - jQuery 图片跟随鼠标浮动