JavaScript:随时间更改 Div 背景
我的网站上有一个广告部分。对于大多数用户来说,这加载得很好并且按预期工作。但是,如果用户安装了某种广告拦截器,则广告不会显示,并且会显示网站的空白区域。
我的解决方案?我想在广告下方放置一个背景图片,要求用户考虑仅在该网站上启用广告。该图像并不引人注目,并且使用户可以选择是否支持他们正在访问的网站。通过简单的 CSS,我可以使这项工作很好(只需使用背景图像就可以了)。
问题是广告需要一点时间才能加载(对于某些用户来说大约需要一秒钟左右)。我不希望在广告有机会加载之前显示此背景图像,因此我想在一定时间(可能是 2-3 秒)后更改 div 的背景。
这是我当前对 JavaScript 函数的尝试:
<script type="text/javascript">
function show_banner(){
document.getElementById('banner').style.background="url('images/banner_bg.png')";
}
function show_banner_delay(){
setTimeout("show_banner()", 3000);
}</script>
这是 HTML 代码:
<div id="banner-wrap">
<div id="banner">
<!--Google AdSense Code Here-->
</div>
</div>
我觉得我可能只是缺少一些基本语法的东西,但我似乎无法弄清楚!
感谢您的帮助!
I have an advertisement section on my website. For most users, this loads just fine and works as intended. However, if the user has an ad-blocker of sorts, the advertisement doesn't show up and an empty area of the site is displayed.
My solution? I would like to place a background image under the advertisement that asks users to consider enabling advertisements on this site only. This image is un-obtrusive, and gives the user a choice whether or not to support the site they are visiting. Through simple CSS, I can make this work just fine (just use background-image and it's good).
The problem is that advertisements take a little bit to load (about a second or so for some users). I don't want this background-image to be displayed BEFORE the advertisement has a chance to load, so I'd like to change the background of the div after a certain amount of time (2-3 seconds, maybe).
Here's my current attempt at a JavaScript function:
<script type="text/javascript">
function show_banner(){
document.getElementById('banner').style.background="url('images/banner_bg.png')";
}
function show_banner_delay(){
setTimeout("show_banner()", 3000);
}</script>
This is the HTML code:
<div id="banner-wrap">
<div id="banner">
<!--Google AdSense Code Here-->
</div>
</div>
I feel like I am probably just missing something as far as basic syntax here, but I can't seem to figure it out!
THANKS FOR ANY HELP!!!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
删除 show_banner_delay 函数。
测试一下:
Drop the show_banner_delay function.
Test it:
试试这个:
setTimeout(show_banner, 3000);
另外,为了更好的测量,将
...style.background = url...
更改为...style .backgroundImage = url...
除非您要更改背景的其他属性。Try this:
setTimeout(show_banner, 3000);
Also, just for good measure change
...style.background = url...
to...style.backgroundImage = url...
unless you're going to change other attributes of the background.