是否可以用CSS过渡来让一个文本段落在页面加载时淡入?
我非常喜欢http://dotmailapp.com/上的效果,希望用CSS来实现类似的效果。该域名后来被收购,不再有上述效果。可以在Wayback Machine上看到一个存档的副本。
有这个标记。
<div id="test">
<p>This is a test</p>
</div>
有以下的CSS规则。
#test p {
opacity: 0;
margin-top: 25px;
font-size: 21px;
text-align: center;
-webkit-transition: opacity 2s ease-in;
-moz-transition: opacity 2s ease-in;
-o-transition: opacity 2s ease-in;
-ms-transition: opacity 2s ease-in;
transition: opacity 2s ease-in;
}
如何在加载时触发过渡?
如果你正在寻找一个自我激励的过渡,那么你应该使用CSS 3 Animations。它们也不被支持,但这正是它们的用途。
#test p {
margin-top: 25px;
font-size: 21px;
text-align: center;
-webkit-animation: fadein 2s; /* Safari, Chrome and Opera > 12.1 */
-moz-animation: fadein 2s; /* Firefox < 16 */
-ms-animation: fadein 2s; /* Internet Explorer */
-o-animation: fadein 2s; /* Opera < 12.1 */
animation: fadein 2s;
}
@keyframes fadein {
from { opacity: 0; }
to { opacity: 1; }
}
/* Firefox < 16 */
@-moz-keyframes fadein {
from { opacity: 0; }
to { opacity: 1; }
}
/* Safari, Chrome and Opera > 12.1 */
@-webkit-keyframes fadein {
from { opacity: 0; }
to { opacity: 1; }
}
/* Internet Explorer */
@-ms-keyframes fadein {
from { opacity: 0; }
to { opacity: 1; }
}
/* Opera < 12.1 */
@-o-keyframes fadein {
from { opacity: 0; }
to { opacity: 1; }
}
所有现代浏览器和Internet Explorer 10(及以后):http://caniuse.com/#feat=css-animation
另外,你可以使用jQuery(或普通的JavaScript;见第三个代码块)来改变加载时的类别。
$("#test p").addClass("load");
#test p {
opacity: 0;
font-size: 21px;
margin-top: 25px;
text-align: center;
-webkit-transition: opacity 2s ease-in;
-moz-transition: opacity 2s ease-in;
-ms-transition: opacity 2s ease-in;
-o-transition: opacity 2s ease-in;
transition: opacity 2s ease-in;
}
#test p.load {
opacity: 1;
}
document.getElementById("test").children[0].className += " load";
所有现代浏览器和Internet Explorer 10(及以后):http://caniuse.com/#feat=css-transitions
或者,你可以使用.Mail使用的方法。
$("#test p").delay(1000).animate({ opacity: 1 }, 700);
#test p {
opacity: 0;
font-size: 21px;
margin-top: 25px;
text-align: center;
}
jQuery 1.x。所有现代浏览器和Internet Explorer 6(及以后): http://jquery.com/browser-support/
_jQuery 2.x__:所有现代浏览器和Internet Explorer 9(及以后): http://jquery.com/browser-support/
这种方法是最具交叉兼容性的,因为目标浏览器不需要支持CSS 3过渡或动画。
你可以使用onload=""
HTML属性,并使用JavaScript来调整你的元素的不透明度风格。
让你的CSS按照你的建议进行。编辑你的HTML代码,以。
<body onload="document.getElementById(test).style.opacity='1'">
<div id="test">
<p>This is a test</p>
</div>
</body>
这也可以在加载完成后淡入整个页面:
HTML。
<body onload="document.body.style.opacity='1'">
</body>
CSS:
body{
opacity: 0;
transition: opacity 2s;
-webkit-transition: opacity 2s; /* Safari */
}
查看W3Schools网站。过渡和一篇关于用JavaScript改变样式的文章。
为了回答@A.M.K'关于如何在没有jQuery的情况下进行转换的问题。一个非常简单的例子,我把它放在一起。如果我有时间再考虑一下,我也许可以完全消除JavaScript代码。
<style>
body {
background-color: red;
transition: background-color 2s ease-in;
}
</style>
<script>
window.onload = function() {
document.body.style.backgroundColor = '#00f';
}
</script>
<body>
<p>test</p>
</body>