Simple jquery .hover() method for each class element

我怕爱的太早我们不能终老 提交于 2020-01-04 01:50:12

问题


haven't done much jquery and ran into a problem. I'd like to bind hover event for all div's with class .social-tile. I do it like this:

$(function(){
    var social_default = $('.social-tile').css('margin-right');
    $('.social-tile').each(function(){
        $(this).hover(function(){
            $(this).animate({
                'margin-right': '0px' 
            },500);
        },function(){
            $(this).animate({
                'margin-right': social_default 
            },500);
        });
    });
});

When I hover over one element, animations for all divs are triggered and they move all at one time. I'd like to animate only specific element which I hover.

Probably there is a really easy fix here, thank you.


回答1:


$(function() {
    $('.social-tile').hover(
    function() {
        $(this).data('prev-margin-right', $(this).css('margin-right') );
        $(this).animate({
            'margin-right': '0px'
        }, 500);
    }, function() {
        $(this).animate({
            'margin-right': $(this).data('prev-margin-right')
        }, 500);
    });
});



回答2:


try this, sorry - working demo here: http://jsfiddle.net/8vFAD/1/

$('.social-tile').live('mouseover', function(){
    $(this).animate({ 'margin-left': '15px'} ,500).animate({ 'margin-left': '30px'} ,500);
});



回答3:


Ok your variable social_default, has .socialtile in it, which will call to all the divs assigned to it, change that to (this).



来源:https://stackoverflow.com/questions/5518815/simple-jquery-hover-method-for-each-class-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!