img src的Javascript变量?

时间:2017-09-20 09:06:13

标签: javascript html image

我找不到这段代码的问题,今晚我遇到了太多麻烦,有人可以帮帮我吗?

<html>
    <script type="text/javascript">
      var image = new Array ();
      image[0] = "header1.png";
      image[1] = "header2.png";
      image[2] = "header3.png";
      image[3] = "header4.png";
      var size = image.length
      var x = Math.floor(size*Math.random())
      var backgroundImageFile = image[x];
      var backgroundImageUrl = "url('" + backgroundImageFile + "')";
      $('#header-image').css('background-image', 'backgroundImageUrl');
      function op()
    {
    document.getElementById('header-image').innerHTML=backgroundImageUrl;
    }
    </script>
    <body onload="op();">
    <img src="backgroundImageFile">
    </body>
    </html>

2 个答案:

答案 0 :(得分:2)

你可以试试这个:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    var image = new Array ();
      image[0] = "https://www.w3schools.com/angular/pic_angular.jpg";
      image[1] = "https://www.w3schools.com/images/colorpicker.gif";
      image[2] = "https://www.w3schools.com/angular/pic_angular.jpg";
      image[3] = "https://www.gstatic.com/images/branding/googlelogo/2x/googlelogo_dark_color_84x28dp.png";
      var size = image.length
      var x = Math.floor(size*Math.random());
      var backgroundImageFile = image[x];
$('#imageId')[0].setAttribute('src',backgroundImageFile);
});

</script>
</head>
<body>
 //displays circle with dimensions 

    image here:
  <img src="backgroundImageFile" id="imageId">

</body>
</html>

答案 1 :(得分:1)

请找到解决方案:我认为您正在寻找解决方案。

&#13;
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
    <script type="text/javascript">
      var image = new Array ();
      image[0] = "header1.png";
      image[1] = "header2.png";
      image[2] = "header3.png";
      image[3] = "header4.png";
      var size = image.length
      var x = Math.floor(size*Math.random())
      var backgroundImageFile = image[x];
      var backgroundImageUrl = "url('" + backgroundImageFile + "')";
      $('#header-image').css('background-image', 'backgroundImageUrl');
      function op()
    {
    document.getElementById('header-image').innerHTML=backgroundImageUrl;
    }
    </script>
    <body onload="op();">
    <img src="backgroundImageFile">
    <div id="header-image"></div>
    </body>
    </html>
&#13;
&#13;
&#13;