在页面加载时触发CSS3转换

我试图通过CSS3宽度转换实现页面加载的加载效果。 这是演示

HTML

CSS

 .skill-bar { width: 57%; float: left; height: 11px; border-radius: 5px; position: relative; margin: 6px 0 12px 0; border: 2px solid #00edc2; } .skill-bar span { background: #00edc2; height: 7px; border-radius: 5px; display: inline-block; } .skill-bar span.w70 { width: 70%; } .skill-bar span { width: 0; transition: width 1s ease; -webkit-transition: width 1s ease; background-color: #00edc2; } 

它没有按预期工作。 我需要在加载页面时进行转换。

但是当我检查元素并检查/取消选中跨度的width时,我得到了效果。

如何对页面加载产生相同的影响?

在此处输入图像描述

您可以在没有JavaScript的情况下实现效果,并且使用CSS动画没有任何兼容性问题

 

 .skill-bar { width: 57%; float: left; height: 11px; border-radius: 5px; position: relative; margin: 6px 0 12px 0; border: 2px solid #00edc2; } .skill-bar span { background: #00edc2; height: 7px; border-radius: 5px; display: inline-block; } .skill-bar span { animation: w70 1s ease forwards; } .skill-bar .w70 { width: 70%; } @keyframes w70 { from { width: 0%; } to { width: 70%; } } 

webkit的小提琴: http : //jsfiddle.net/ySj7t/

通过从span中删除类并在JavaScript中设置它,浏览器将应用转换,但这仅适用于第一个.skill-bar 。 另外.getElementsByClassName在IE8或更低版本中不起作用。

HTML

 

JavaScript的

 document.getElementsByClassName('skill-bar')[0].getElementsByTagName('span')[0].className = 'w70'; 

(所以只需在HTML之后将其包装在元素中,或者在加载页面时查看run函数

纯JavaScript演示

您可能需要一个jQuery(或其他框架)解决方案来确保跨浏览器兼容性,但这会引入对框架的依赖。 如果你已经包含jQuery那么好了。 如果不是,您将需要先包含该库,然后使用:

jQuery的

 $(window).load(function(){ $('.skill-bar span').addClass('w70'); }); 

jQuery演示

右键单击输出框并选择View frame source查看输出代码。

通过javascript添加类:

 $(".skill-bar span").addClass("w70"); 

在这里看小提琴 。