jQuery 加载时淡入页面
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19962465/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Fading in page on load
提问by Sam Friday Welch
I am trying to use j-query to fade in my pages body upon load, however for some reason the body's background image is not being affected by the j-query. Please see the code I have below:
我正在尝试使用 j-query 在加载时淡入我的页面正文,但是由于某种原因,正文的背景图像不受 j-query 的影响。请参阅我在下面的代码:
J-Query Code in head section:
head 部分中的 J-Query 代码:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('body').fadeIn(2000);
});
</script>
CSS Code:
CSS 代码:
body
{
overflow:hidden;
background:url('body.png') no-repeat;
background-size:100%;
display:none;
}
Everything contained within the body (div's / paragraphs / headings etc) fade in on load as per the j-query code, however the body's background image (body.png) loads instantly with the page. Please can anyone suggest what I'm doing wrong with the above code?
正文中包含的所有内容(div 的/段落/标题等)根据 j-query 代码在加载时淡入,但是正文的背景图像 (body.png) 会立即随页面加载。请有人建议我上面的代码做错了什么吗?
回答by Robbie Wxyz
bodybehaves funny. You would need to wrap the contents of the entire page in another divand fade that in.
body举止风趣。您需要将整个页面的内容包装在另一个页面中div并将其淡入。
<body>
<div id="wrapper">
# Page Contents #
</div>
</body>
CSS:
CSS:
#wrapper{
background-image:url('some-image.jpg');
display:none;
}
jQuery:
jQuery:
$(document).ready(function(){
$('#wrapper').fadeIn();
});
See this JSFiddle.
看到这个JSFiddle。
回答by pashri
Like the @ITFarmer wait, you can do it in CSS3, but you could probably also animate the background-image with CSS3 too.
就像@ITFarmer 等待一样,您可以在 CSS3 中完成,但您也可以使用 CSS3 为背景图像设置动画。
@keyframes fadein {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@keyframes fadeinbg {
from {
background-image: none;
}
to {
background:url('body.png') no-repeat;
}
}
.container {
animation: fadein 2s;
}
.body {
animation: fadeinbg 2s;
回答by ITFarmer
I'm not sure if it would also affect the background image, but you could do the fade-in effect also without jQuery. At least in browsers which support CSS3:
我不确定它是否也会影响背景图像,但您也可以在没有 jQuery 的情况下实现淡入效果。至少在支持 CSS3 的浏览器中:
@keyframes fadein{
from{opacity:0;}
to{opacity:1;}
}
.someElement{
animation: fadein 2s;
}

