jQuery更改CSS背景位置和鼠标hover/ mouseout
我有一个由单个图像组成的菜单(例如,精灵)。 为了显示hover图像,我只需将背景图像向下移动。 我希望这个效果由jQuery和动画控制。
这是一个示例菜单项。
这就是我正在玩弄的东西。 我是jQuery的新手,并且在使用正确的选择器时遇到了问题。
$(document).ready(function(){ $('#home a'); // Set the 'normal' state background position .css( {backgroundPosition: "0 0"} ) // On mouse over, move the background .mouseover(function(){ $(this).stop().animate({backgroundPosition:"(0 -54px)"}, {duration:500}) }) // On mouse out, move the background back .mouseout(function(){ $(this).stop().animate({backgroundPosition:"(0 0)"}, {duration:500}) }) });
你能指出我做错了什么吗? 我知道选择器可能不正确,但我很难弄清楚如何操纵锚。
如果你没有动画转换 – 并且给出了我被分组为精灵的图像种类,我不知道为什么你会这样做 – 那么你需要这样的东西:
$(document).ready(function(){ $('#home a') // On mouse over, move the background on hover .mouseover(function() { $(this).css('backgroundPosition', '0 -54px'); }) // On mouse out, move the background back .mouseout(function() { $(this).css('backgroundPosition', '0 0'); }) });
现在,如果您正在尝试设置动画,那么您的CSS语法和“动画”调用都会有错误的语法。
$(document).ready(function(){ $('#home a') // On mouse over, move the background on hover .mouseover(function(){ $(this).stop().animate({backgroundPosition: "0 -54px"}, 500); }) // On mouse out, move the background back .mouseout(function(){ $(this).stop().animate({backgroundPosition: "0 0"}, 500); }) });
再一次,我怀疑jQuery是否能够为你制作“backgroundPosition”动画,但是我不经常做“animate()”并且jQuery总是让我感到惊讶。
编辑:这是一个页面: http : //snook.ca/archives/javascript/jquery-bg-image-animations/
{backgroundPosition:“(0 -54px)”
(你不想在那里使用括号.CSS background-position
规则中没有括号。)
在任何情况下,jQuery都不知道如何为像backgroundPosition
这样的复合值设置动画。 在IE中,您可以使用backgroundPositionY
访问它,作为一个简单的值,jQuery 可以设置动画。 然而,这是非标准的,并不适用于其他地方。
这是一个声称修复它的插件 。
我喜欢这种方法(只是css)
.maintopbanner a:hover{ background-position: -200px 0 !important;} .maintopbanner a { -webkit-transition: all .2s ease; -moz-transition: all .2s ease; transition: all .2s ease; }
我想你的背景必然会被li
? 但是this
被设置为选择器的a
,所以如果我的假设是正确的,你需要将代码更改为
$(document).ready(function(){ $('#home a') // On mouse over, move the background on hover .mouseover(function(){ $(this).parent().stop().animate({backgroundPosition:"(0 -54px)"}, {duration:500}) }) // On mouse out, move the background back .mouseout(function(){ $(this).parent().stop().animate({backgroundPosition:"(0 0)"}, {duration:500}) }) });
$('#home a') .mouseenter(function(){ $(this).parent().stop().animate({backgroundPosition:"(0 -54px)"},500) }) .mouseleave(function(){ $(this).parent().stop().animate({backgroundPosition:"(0 0)"},500) })
//尽可能使用MouseEnter和MouseLeave,您不需要使用当前版本的jQuery输出持续时间。 希望这可以帮助。