在jquery中改变或动画高度为css默认值



我有一个响应式网站不同的高度设置的标题栏。在我的javascript中,我将此值更改为固定大小:

$('#header').animate({marginTop: 0, height:80});

但是在我的代码的另一点,我希望它恢复到原始状态。我如何使它恢复到默认行为?换句话说,动画remove inline css…

I tried

$('#header').animate({marginTop: 20, height:'inherit'});

但是这不起作用

原来的css是这样的:

#header { margin-top:20px; width:100%; height: 80px; background-color: #000; }
@media only screen and (min-width: 768px) and (max-width: 960px) 
{   
#header{height:100px;}
}
@media only screen and (max-width: 767px) 
{
#header{height:auto; padding-bottom: 1px;}
}

解决方案1:


存储高度值:
这是不可能做到的,因为很多用户在存储值的时刻和恢复存储值的时刻之间调整了他们的窗口大小。

解决方案2:


动画到'nothing',只是一个空字符串,如果失败,Jquery将其解释为0,并将高度动画到0像素。

可以这样使用:

var original = $('#header').css('height');//gets original height
$('#header').animate({marginTop: 0, height:80});

然后回复为:

$('#header').animate({marginTop: 0, height:original});

考虑到你有像下面这样的HTML

<div class="item">
    <div class="block"></div>
    <div class="info">
           My info
    </div>
</div>

你可以这样做:

jQuery(document).ready(function($) {
    $(".item").mouseleave(function(){
        $(this).find('.info').stop().css('marginTop', '0');
    }).mouseenter(function(){
        $(this).find('.info').animate({ marginTop: '-50px', opacity: 0.5 }, 1000);
    });
});
演示

尝试不设置height值或将height值保留为空

您必须将原始值存储在某个地方。我推荐这个-

$('#header').data('height', $(this).height()).animate({marginTop: 0, height:80});

当你准备恢复-

var oldHeight = $('#header').data('height');
$('#header').animate({marginTop: 20, height: oldHeight });

编辑,

div还有其他的内联样式吗?

如果没有,您可以简单地使用removeAttr并删除style属性。

最新更新