简体   繁体   中英

Clear top value of an element in jquery.animate()

I have this css:

.hacer .contenido .caja .texto {
    position: absolute;
    bottom: -30px;
}

and I have this jquery

 var cajasHacer = $('.hacer').find('.contenido').find('.caja');

        cajasHacer.each(function () {

        $(this).mouseenter(function() {
            $(this).find('.texto').animate({top: '40px'} , 300);
        });

        $(this).mouseleave(function() {
            $(this).find('.texto').animate({ top: 'auto'} , 300);
        });
    });

I have used values for top: initial,unset and auto, but it doesn't clear the top value of the element and travel to bottom again when mouse leaves.

You can reset the top value through removing the style attribute values using .removeAttr() method.

var cajasHacer = $('.hacer').find('.contenido').find('.caja');

    cajasHacer.each(function () {

    $(this).mouseenter(function() {
        $(this).find('.texto').animate({top: '40px'} , 300);
    });

    $(this).mouseleave(function() {
        $(this).find('.texto').removeAttr('style');
    });

});

DEMO

I think, you should store the initial top value of the element in a variable. So, when the mouseleave event triggers, you can add it to your element.

var topPos = $(element).offset().top;

and in your code:

var cajasHacer = $('.hacer').find('.contenido').find('.caja');

        cajasHacer.each(function () {

        $(this).mouseenter(function() {
            $(this).find('.texto').animate({top: '40px'} , 300);
        });

        $(this).mouseleave(function() {
            $(this).find('.texto').animate({ top: topPos} , 300);
        });
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM