在 JavaScript 函数中添加时间延迟以实现淡入淡出效果
我正在寻找一个可以慢慢淡入以隐藏图像加载的网站。现在,我已经设法获取一些可以淡入的 JavaScript,但它会在页面加载时立即启动,因此您在加载页面时仍然可以看到各个元素正在加载。
我想做的是在开始淡入之前添加一秒左右的延迟。
这是我现在得到的:
<style>fadein{filter:alpha(opacity=0);opacity:0}</style>
<script>
function fadein(){var fade=0, fadein=document.getElementById("index-wrappper").style,ms=(fadein.opacity==0)?0:1, pace=setInterval(Fade,20);
function Fade() {if(fade<100){fade+=1;if(ms)fadein.filter="alpha(opacity="+fade+")";else fadein.opacity=(fade/100)} else clearInterval(pace)}};
window.onload=fadein;
</script>
我怀疑我需要以某种方式在 Function fade 中添加延迟,因为 Fadein 是设置加载时 div 的不透明度为 0。
但我到底需要放什么东西呢?我对 javascript 的了解很少甚至没有(我真的需要温习一下),并且非常感谢任何有关这方面的帮助。
I'm looking to make a website that slowly fades in to hide the loading of the images. Now I've managed to get some javascript that does the fade in but it starts immediatly when the page loads so you still see the individual elements loading when you load the page.
What I would like to do is to add a delay of a second or so before it starts fading in.
Here is what i've got now:
<style>fadein{filter:alpha(opacity=0);opacity:0}</style>
<script>
function fadein(){var fade=0, fadein=document.getElementById("index-wrappper").style,ms=(fadein.opacity==0)?0:1, pace=setInterval(Fade,20);
function Fade() {if(fade<100){fade+=1;if(ms)fadein.filter="alpha(opacity="+fade+")";else fadein.opacity=(fade/100)} else clearInterval(pace)}};
window.onload=fadein;
</script>
I suspect that I need to add the delay in Function fade somehow since Fadein is what set the opacity of the div to 0 on load.
But what exactly do i need to put there? I have slim to none javascript knowledge (which i really need to brush up) and would really appreciate any help with this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
首先,Javascript不是Java。
您的问题的一个简单答案是:使用 setTimeout 和clearTimeout。
但坦率地说,我敦促您不要重新发明轮子,而是使用像 jQuery 这样的库,这些库的构建是为了使此类操作更容易并支持所有主要浏览器。在 jQuery 中你可以简单地写
First of all, Javascript is not Java.
A simple answer to your question is: use setTimeout and clearTimeout.
But frankly I would urge you not to reinvent the wheel, but to use libraries like jQuery that are built to make such actions easier and support all major browsers. In jQuery you could simply write
试试这个:
这会在页面加载后延迟 1 秒淡入。
Try this:
This delays the fade in with 1 sec, after page load.
应该可以解决问题。
should do the trick.
您是否考虑过使用 jQuery 库?
它免费、易于使用、完全满足您的需求,并且跨浏览器兼容。许多网站(包括这个网站)都使用它,因此如果您无法让它执行您想要的操作,您将能够获得帮助。
请注意,您问题中发布的脚本仅适用于 Internet Explorer,由 less 使用超过 50% 的人使用网络浏览器。
Have you considered using the jQuery library?
It's free, easy to use, does exactly what you want and is cross-browser compatible. Many sites (including this one) use it so you'll be able to get help if you can't get it to do what you want.
Note that the script posted in your question would work only on Internet Explorer, used by less than 50% of people as a web browser.