【问题标题】:Jascript random background static page HTMLJavascript随机背景静态页面HTML
【发布时间】:2021-12-30 19:27:19
【问题描述】:

我从 2 小时开始尝试将我的 PHP 代码更改为静态页面“html”的 JavaScript,但我看到了示例,但它不起作用。我只想在加载页面中更改背景图片。

你能帮帮我吗?

那是我的代码。

  window.onload = choosePic;

var myPix = new Array("images/lion.jpg","images/tiger.jpg","images/bear.jpg");

function choosePic() {
     var randomNum = Math.floor(Math.random() * myPix.length);
     document.getElementById("myPicture").src = myPix[randomNum];

在我的 HTML 中

但没有任何效果。

【问题讨论】:

  • 假设你放在那里的是你唯一的代码,你只是打错了,忘记了你的右括号。不过,对于未来,您应该为您的问题添加更多细节。例如,您的 html 文件、您遇到的特定错误等。编辑:我之前在拼写错误这个词中打错了字,此时我已经失去了对自己的所有尊重

标签: javascript image random


【解决方案1】:

它对我有用。这是那个代码。您可以参考这段代码并检查出了什么问题它正在工作,如果是,那么您在数组中提供了错误的路径并更正它们。

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title></title>
</head>
<body>
    <div>
        <img id='myPicture' src=''>
    </div>

    <script type="text/javascript">
        window.onload = choosePic;

        var myPix = new Array('https://i.imgur.com/pbyO8uHb.jpg', 'https://i.imgur.com/KgVNwGhb.jpg', 'https://i.imgur.com/Tj1bKhLb.jpg')

        function choosePic() {
            
            var randomNum = Math.floor(Math.random() * myPix.length);
            document.getElementById("myPicture").src = myPix[randomNum];
        }

    </script>
</body>
</html>

【讨论】:

  • 是的,如果我将脚本代码放入我的 html 中,它会起作用,但如果我将 js“picture.js”放在外部并调用它,那将不起作用。其他脚本完美运行
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多