这个问题在这里已有答案:
这是一个简单的CSS过渡。
div.simple_transition {
width: 100px;
height: 100px;
background: red;
-webkit-transition: width 5s;
/* For Safari 3.1 to 6.0 */
transition: width 5s;
&:hover {
width: 100%;
}
}
<h1>Simple Transition</h1>
<p>NoJS Animation starts when hovering the element</p>
<div class="simple_transition"></div>
<p>
<b>Note:</b> This example does not work in Internet Explorer 9 and earlier versions.</p>
所以我希望它以编程方式启动转换,例如在浏览器加载页面之后不使用鼠标悬停css选择器。我知道我可以用javascript做到这一点,我设法用一个简单的代码做到这一点。
//Based on https://www.w3schools.com/css/tryit.asp?filename=trycss3_transition1
$(document).ready(function() {
var elm = $('div.simple_transition');
elm.attr('class', 'should-be-likethis');
console.log('working on it');
});
div.simple_transition {
width: 100px;
height: 100px;
background: red;
-webkit-transition: width 5s;
/* For Safari 3.1 to 6.0 */
transition: width 5s;
&:hover {
width: 100%;
}
}
.should-be-likethis {
-webkit-transition: width 5s;
/* For Safari 3.1 to 6.0 */
transition: width 5s;
width: 100%;
height: 100px;
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Simple Transition</h1>
<p id='text'>With jQuery animation starts without hovering the element</p>
<div class="simple_transition"></div>
<p><b>Note:</b> This example does not work in Internet Explorer 9 and earlier versions.</p>
我可以在不使用CSS的情况下使用javascript吗?事实上,在我目前的项目中,我已经使用javascript(ajax)来处理一些与数据相关的查询,我也在使用sass编译器,所以我更愿意编写与CSS中的样式相关的所有内容。
我更改了您的类名以匹配新行为(动画,而不是转换)。我们正在从100px
动画到视口的整个宽度。
html, body { margin: 0; } /* Prevent scrollbar */
div.simple_animation {
width: 100px;
height: 100px;
background: red;
animation: 5s loading forwards;
}
@keyframes loading {
to {
width: 100vw;
}
}
<div class="simple_animation"></div>
CSS
.js-loading *,
.js-loading *:before,
.js-loading *:after {
animation-play-state: paused !important;
}
我已经离开了网络开发,但我认为这适用于大多数现代浏览器