1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 5 <title>用jq实现鼠标移入按钮背景渐变其他的背景效果</title> 6 </head> 7 <style> 8 *{ margin:0; padding:0;} 9 .btn{ 10 width: 160px; 11 height: 41px; 12 background: url(recommend_read_more.png) no-repeat; /*背景图片要竖直拼起来*/ 13 display:block; 14 position: relative;/*一定要设置相对定位*/ 15 } 16 .move_fade { 17 position: absolute;/*鼠标移入显示另外一个标签的类名设置样式*/ 18 width: 100%; 19 height: 100%; 20 opacity: 0; 21 filter: alpha(opacity=0); 22 top: 0px; 23 left: 0px; 24 } 25 </style> 26 <body> 27 28 29 <a href="case.aspx" class="btn "></a> 30 31 32 <script type="text/javascript" src="js/jquery.js"></script> 33 <script> 34 function moveFade(obj, back_y) { 35 36 $(obj).each(function () { 37 var this_event = null; 38 $(this).html($(this).html() + "<span class='move_fade'></span>");//添加另外一个标签名,并且设置绝对定位 39 var xy; 40 if ($(this).css('background-position') == undefined) { //判断背景的位置,根据当前的背景获取鼠标移入的背景位置 41 xy = [$(this).css('background-position-x'), $(this).css('background-position-y')]; 42 } 43 else { 44 xy = $(this).css('background-position').split(' '); 45 } 46 47 $('.move_fade', this).css({ 48 'background-image': $(this).css('background-image'), 49 'background-position': xy[0] + ' ' + back_y 50 }).hover(function () { 51 var obj = this; 52 function go() { 53 54 var v = $(obj).css('opacity') - 0 + 0.1; 55 56 if (v <= 1 && this_event == 'in') { 57 if (v > 0.9) { 58 v = 1; 59 } 60 $(obj).css({ 61 'opacity': v, 62 'filter': 'alpha(opacity=' + (v * 100) + ')' 63 }); 64 setTimeout(go, 50); 65 } 66 } 67 this_event = 'in'; 68 go(); 69 70 }, function () { 71 72 var obj = this; 73 function go() { 74 var v = $(obj).css('opacity') - 0.1; 75 if (v < 0.1) { v = 0; } 76 if (v >= 0 && this_event == 'out') { 77 $(obj).css({ 78 'opacity': v, 79 'filter': 'alpha(opacity=' + (v * 100) + ')' 80 }); 81 82 setTimeout(go, 50); 83 } 84 } 85 this_event = 'out'; 86 go(); 87 }); 88 }); 89 } 90 91 $(function(){ 92 moveFade('.btn', '-41px')//对象,背景位置y轴 93 }) 94 </script> 95 </body> 96 </html>