0

我希望用户将鼠标悬停在一个链接上,该链接有一个名为图片的类和动画的跨度(增加填充顶部),这是我到目前为止所做的代码,但是当用户将鼠标悬停在它上面时,它会为它们设置动画,我只希望它为用户悬停的那个动画。

$('.picture').each(function(){
    $('.picture').hover(function(){
        $('.picture span').animate({
            'padding-top' : '20px'
        },'fast');
    });

    $('.picture').mouseout(function(){
        $('.picture span').animate({
            'padding-top' : '10px'
        },'fast');
    });
});

任何帮助将不胜感激我认为它在每个功能的某个地方我出错了,但我不确定。可以在这里找到它的链接:http: //bathroomsyork.co.uk/

4

4 回答 4

5

我看不出你的外each()呼有什么好处。你应该试试这个:

$('.picture').hover(
    function() {
        $(this).find('span').animate({'padding-top' : '20px'},'fast');
    },
    function() {
        $(this).find('span').animate({'padding-top' : '10px'},'fast');
    }
);

请注意,我们选择所有图片类元素,然后使用hover()函数的两个参数来指定mouseentermouseleave事件回调。

在每个回调中,获取当前悬停元素的子跨度$(this),并执行动画。

于 2013-01-16T23:34:33.340 回答
3

You don't need to iterate over all elements, you can bind the event handler to all the matched elements at the same time.

Also, use $('span', this) to select the correct <span> from the hovered element.

$('.picture').on({
  mouseenter: function () {
    $('span', this).animate({
      'padding-top': '20px'
    }, 'fast');
  },
  mouseout: function () {
    $('span', this).animate({
      'padding-top': '10px'
    }, 'fast');
  }
});
于 2013-01-16T23:28:08.133 回答
1

这最终奏效了伙计们:

$('.picture').each(function(){
    $(this).hover(function(){
        $('span', this).animate({
            'padding-top' : '20px'
        },'fast');
    }, function(){
        $('span', this).animate({
            'padding-top' : '10px'
        },'fast');
    });
});

当我尝试使用 on() 的示例时,出现控制台错误,这与我以前从未见过的完全一样是什么?

不管怎么说,还是要谢谢你。

于 2013-01-16T23:57:52.103 回答
0

You don't need each.

$('.picture').on('mouseenter mouseleave', function(e){
    var padding = e.type == 'mouseenter' ? '20px' : '10px';
    $('span', this).animate({
        'padding-top' : padding
    },'fast');
});
于 2013-01-16T23:26:15.507 回答