jQuery更改CSS背景位置和鼠标悬停/ mouseout [英] jQuery change CSS background position and mouseover/mouseout

查看:89
本文介绍了jQuery更改CSS背景位置和鼠标悬停/ mouseout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个由单个图像组成的菜单(例如,精灵)。为了显示悬停图像,我只需将背景图像向下移动。我希望这个效果由jQuery和动画控制。

I have a menu composed of a single image (e.g., sprites). In order to display the hover image, I simply move the background image down. I'd like this effect to be controlled by jQuery and animated.

这是一个示例菜单项。

 <ul>
  <li id="home"><a href="#"></a></li>
 </ul>

这就是我正在玩弄的东西。我是jQuery的新手,我在使用正确的选择器时遇到了问题。

This is what I'm toying with. I'm very new to jQuery and am having problems getting the proper selector going.

 $(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})
   })

 });

你能指出我做错了什么吗?我知道选择器可能不正确,但我很难搞清楚如何操纵锚点。

Could you point out what I'm doing wrong? I know the selector is probably incorrect but I'm having a hard time figuring out how to manipulate the anchor.

推荐答案

如果你没有动画过渡动画—鉴于我把这些图像分组为精灵,我不知道为什么你会这样做—然后你会想要这样的东西:

If you were not animating the transitions — and given the kinds of images I've grouped as sprites, I don't know why you'd ever do that — then you'd want something like this:

$(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的语法和animate的调用都有错误。

Now, if you are trying to animate that, then you've got bad syntax for the CSS and for the calls to "animate".

$(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总是让我感到惊讶。

Again, I am doubtful that jQuery is going to be able to animate "backgroundPosition" for you, but then I don't do "animate()" very often and jQuery always manages to surprise me.

编辑:这是一个页面:< a href =http://snook.ca/archives/javascript/jquery-bg-image-animations/ =noreferrer> http://snook.ca/archives/javascript/jquery-bg-image-animations /

这篇关于jQuery更改CSS背景位置和鼠标悬停/ mouseout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆