元素维度的CSS3过渡不起作用,从百分比或自动到像素大小

时间:2015-05-20 08:15:29

标签: css css3 css-transitions

我正在构建一个单页网站,在“开始屏幕”上显示80%屏幕宽度的矢量图形。用户向下滚动后,图形将转换到页面顶部的导航栏,并且应获得50px的高度。应该使用CSS3过渡动画从大尺寸到小尺寸的过渡。

但是,将元素从百分比或自动值缩放到固定像素值时,CSS转换似乎不起作用,反之亦然。我做了一个jsfiddle来证明这种效果。虽然div的高度转换得很好,但宽度根本没有动画。

使用像素宽度作为图像的初始大小不是响应设计原因的选项。代码:

<!DOCTYPE html>
<html>
<head>
    <title></title>

    <style type="text/css">
        html, body{
            background-color: #010101;
            height: 100%;
        }
        .navbar--logo-item{
            background-color: #fff;
            height: 10px;
            width: 80%
            -moz-transition: all 0.5s ease-in-out;
            transition: all 0.5s ease-in-out;
        }
        .navbar--logo-item.small{
            height: 50px;
            width: 200px;
        }
    </style>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $('#toggle').click(function(){
                $('.navbar--logo-item').toggleClass('small');
            });
        });
    </script>
</head>
<body>
    <div class="navbar--logo-item"></div>
    <button id="toggle">
        Toggle Logo
    </button>
</body>
</html>

2 个答案:

答案 0 :(得分:1)

在现代浏览器中,可以使用calc。

来解决

只要它是均匀的,您就可以转换计算值。 您的案例可以用同样的方式表达如下

.navbar--logo-item{
    width: calc(80% + 0px);
}
.navbar--logo-item.small{
    width: calc(0% + 200px);
}

请注意,2计算是相似的(它们总和百分比和像素值),但同时结果与您已有的结果相同

fiddle

获得此功能的另一种常用方法是在较高的原始值​​上设置最大宽度,例如

.navbar--logo-item{
    width: auto;
    max-width: 1000px; /* you don't need to set an accurate value */
}
.navbar--logo-item.small{
    max-width: 200px;   /* no need to set width */
}

答案 1 :(得分:0)

如果您将徽标的宽度设置为&#39;直接父母然后一切都以像素为单位,过渡将按照您的意愿进行。

&#13;
&#13;
$(document).ready(function(){  
    var logo = $('.navbar--logo-item');
    
    function setWidthtoParent(target) {
        var parentWidth = target.parent().width();
        target.css('width', parentWidth);
    }
    
    setWidthtoParent(logo);
    
    $('#toggle').click(function(){
        logo.toggleClass('small');
    });
});
&#13;
html, body{
  background-color: #010101;
  height: 100%;
}
.navbar--logo-item{
  background-color: #fff;
  height: 10px;
  -moz-transition: all 0.5s ease-in-out;
  transition: all 0.5s ease-in-out;
}
.navbar--logo-item.small{
  height: 50px;
  width: 200px !important;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
	<div class="navbar--logo-item"></div>
	<button id="toggle">
		Toggle Logo
	</button>
</body>
&#13;
&#13;
&#13;

这并不理想,因为它需要添加!important声明来覆盖应用的内联样式。在转换发生之前,您还可能会面临调整浏览器窗口大小的风险。更好的解决方案是使用一致的单位(可能会转换父div的宽度,而SVG保持在100%,如this)。