javascript - 使用 javascript 作为背景图片

标签 javascript background-image

我正在寻找其他帖子来解决这个问题(因为当然有)。 但我什至没有成功回答这些其他帖子。

然后,我的问题:

我有以下脚本来随机打开一个图像

<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 不在那里:enter image description here

关于javascript - 使用 javascript 作为背景图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44717807/

相关文章:

javascript - 为什么 "Redirected when going from "/login"to "/"via a navigation guard."出现了?

javascript - 在背景图像中使用正则表达式获取 div

html - Angular 4 背景图像未加载

javascript - 在nodejs中通过带有构造函数的模块公开多个对象

javascript - 节点依赖停止工作

javascript - 在 javascript 中使用 angular.js 的数据绑定(bind)/或更新事件上的 javascript 变量

无法加载 CSS 背景图片 URL

javascript - 使用 jquery/js 将实际页面的 URL 传递到其他页面的输入字段中

image - CSS透明背景图片使用 "data:"

css - Font Awesome Icons 作为列表项或普通背景图像?