我正在寻找其他帖子来解决这个问题(因为当然有)。 但我什至没有成功回答这些其他帖子。
然后,我的问题:
我有以下脚本来随机打开一个图像
<script> function banner()
{var img = new Array();
img[0]='images/hochbau1.jpg';
img[1]='images/hochbau2.jpg';
img[2]='images/hochbau3.jpg';
img[3]='images/hochbau4.jpg';
img[4]='images/hochbau5.jpg';
img[5]='images/hochbau6.jpg';
img[6]='images/hochbau7.jpg';
img[7]='images/hochbau8.jpg';
img[8]='images/hochbau9.jpg';
img[9]='images/hochbau10.jpg';
var n=Math.round((Math.random()*9));
document.write(img[n]);
} </script>
然后,我想在其中放置这些图片(而不是 images/hochbau.jpg):
<div class="section22" style="background-image:url(images/hochbau.jpg); "> </div>
然后,我尝试了这个:
<div class="section22" style="background-image:url(<script> banner(); </script>);"> </div>
或者这个
<div class="section22" style="background-image:url(
<script type="text/javascript" language="javascript">
document.write('images/hochbau'+ Math.round((Math.random()*9)+1)+ '.jpg');
</script>
); "> </div>
然后,我将脚本更改为:
<script> function banner()
{var img = new Array();
img[0]='images/hochbau1.jpg';
img[1]='images/hochbau2.jpg';
img[2]='images/hochbau3.jpg';
img[3]='images/hochbau4.jpg';
img[4]='images/hochbau5.jpg';
img[5]='images/hochbau6.jpg';
img[6]='images/hochbau7.jpg';
img[7]='images/hochbau8.jpg';
img[8]='images/hochbau9.jpg';
img[9]='images/hochbau10.jpg';
var n=Math.round((Math.random()*9));
document.getElementById('myPElement').style.backgroundImage = 'url(img[n])';
} </script>
与以下内容
<div class="section22" id="myPElement">
但没有任何效果......也许我对解决方案不感兴趣,但我被困住了......
如果你有什么观察,请告诉我! 非常感谢您的帮助
最佳答案
您只是没有在脚本中正确引用图像
<script> function banner()
{var img = new Array();
img[0]='images/hochbau1.jpg';
img[1]='images/hochbau2.jpg';
img[2]='images/hochbau3.jpg';
img[3]='images/hochbau4.jpg';
img[4]='images/hochbau5.jpg';
img[5]='images/hochbau6.jpg';
img[6]='images/hochbau7.jpg';
img[7]='images/hochbau8.jpg';
img[8]='images/hochbau9.jpg';
img[9]='images/hochbau10.jpg';
var n=Math.round((Math.random()*9));
document.getElementById('myPElement').style.backgroundImage = 'url(' + img[n] +')'; //you are passing img[n] as string, just change this
} </script>
编辑: 我看到你的页面:http://www.mytmedia.craym.eu/HRPwebsite/index.php
从代码检查中我看到 banner() 函数从未执行过,而且如果我尝试在控制台中执行它,背景图像设置正确但你的 iamges 不在那里:
关于javascript - 使用 javascript 作为背景图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44717807/