我有一个由单个图像组成的菜单(例如,精灵).为了显示悬停图像,我只需将背景图像向下移动.我希望这个效果由jQuery和动画控制.
这是一个示例菜单项.
<ul>
<li id="home"><a href="#"></a></li>
</ul>
Run Code Online (Sandbox Code Playgroud)
这就是我正在玩弄的东西.我是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})
})
});
Run Code Online (Sandbox Code Playgroud)
你能指出我做错了什么吗?我知道选择器可能不正确,但我很难弄清楚如何操纵锚.
Poi*_*nty 13
如果你没有为转换设置动画 - 并且考虑到我将这些图像分组为精灵,我不知道为什么你会这样做 - 那么你需要这样的东西:
$(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');
})
});
Run Code Online (Sandbox Code Playgroud)
现在,如果您正在尝试设置动画,那么您的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);
})
});
Run Code Online (Sandbox Code Playgroud)
同样,我怀疑jQuery是否能够为你动画"backgroundPosition",但是我不经常"动画()"和jQuery总是让我感到惊讶.
编辑:这是一个页面:http://snook.ca/archives/javascript/jquery-bg-image-animations/