简体   繁体   中英

jQuery - Find CSS bottom of div at start, not during animation on hover

I'm finding the CSS value 'bottom' for each of these divs with the class of 'shelf-info-text'. Each of these divs are inside shelf-item.

The bottom value is automatically calculated using another function. On hover I wish bottom to be changed to 0px by way of animation, and then revert to the original bottom. Bottom will be different for every single div.

I have added a little code to find the bottom, however if you hover again mid-animation this finds the bottom before it has returned back to the original state, therefore breaking the animation.

Please advise where I'm going wrong. Thanks.

var $itemBottom = null;
$('.shelf-item').hover(function() {
    $itemBottom = $(this).find('.shelf-info-text').css('bottom');
    $(this).find('.shelf-info-text').stop().animate({ 'bottom': '0px'}, 300);
}, function() {
    $(this).find('.shelf-info-text').stop().animate({ 'bottom': $itemBottom}, 300);
});

Edit : After re-reading the question here's a solution that will get the bottom and save it in a data attribute.

// we loop through all the shelf items and set a data attribute to keep track of it.
$('.shelf-item').each(function(){
    $item = $(this).find('.shelf-info-text');
    $itemBottom = $item.css('bottom');
    $item.data('bottom', $itemBottom);
});

$('.shelf-item').hover(function() {
    $itemBottom = $(this).find('.shelf-info-text').data('bottom');
    $(this).find('.shelf-info-text').stop().animate({ 'bottom': '0px'}, 300);
}, function() {
    $(this).find('.shelf-info-text').stop().animate({ 'bottom': $itemBottom}, 300);
});

I'm too late to the party (because I got distracted making this fiddle ). My approach is the same as @Patsy's but I avoid the .each() loop to set the data-bottom by simply setting it if it doesn't already exist:

var $el = null;
$('.shelf-item').hover(function() {
    $el = $(this).find('.shelf-info-text');
    $el.data('bottom',($el.data('bottom') || $el.css('bottom'))).stop().animate({ 'bottom': '0px'}, 300);
}, function() {
    $el = $(this).find('.shelf-info-text');
    $el.stop().animate({ 'bottom': $el.data('bottom')}, 300);
});

You could store the original bottom value using jQuery.data() . Then your function could check to see if that value had been stored, and never recalculate the bottom (avoiding the mid-animation issue).

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