首页 > 解决方案 > 按钮单击以提供随机图像背景(CSS + JavaScript + JQuery)

问题描述

这是我的代码。我是 JavaScript 新手,所以不知道我真正在做什么。基本上,每次单击按钮时,都会有一个新的梵高细节/图像填充背景。我觉得很多图像都重复了,有时按钮不起作用(每次单击都不会出现新图像)。理想情况下,我希望每次点击都有一个新图像。目前,我只有 10 张图片,但可能会添加更多。谢谢您的帮助。

HTML

<!DOCTYPE html>
<html>
   <head>
      <title>VG java project</title>
      <link rel="stylesheet" type="text/css" href="assets/main.css">
    <script src="assets/jquery-3.5.1.min.js"></script>
      <script type="text/javascript" src="assets/main.js"></script>
   </head>
   <body>
    <div class="container1"></div>
      <div class="container">
         <div class="button">
            Do you like Van Gogh? 
         </div>
         
      </div>
   </body>
</html>

CSS

body {
  font-family: courier new;
  padding: 3rem;
  z-index: 200;
  background: url(gogh4.jpg);
}

.container {
 display: flex;
 flex-direction: column;
 justify-content: center;
 align-items: center;

}

.item {
  max-width: 960px;
  text-align: center;
}

.button {
    position: absolute;
    left: 50px;
    top: 50px;
  border: 7px double;
  border-color: black;
  padding: 20px;
  font-size: 40px;
  background-color: rgb(225, 186, 253);
  opacity: 80%; 
}

.button:hover {
  background-color: rgb(197, 103, 247);
  color: white;
  cursor: pointer;
  opacity: 90%; 
}

.gogh1 {
  background: url(gogh1.jpg);
}

.gogh2 {
  background: url(gogh3.jpg);
}

.gogh3 {
  background: url(gogh3.jpg);
}

.gogh4 {
  background: url(gogh4.jpg);
}

.gogh5 {
  background: url(gogh5.jpg);
}

.gogh6 {
  background: url(gogh6.jpg);
}

.gogh7 {
  background: url(gogh7.jpg);
}

.gogh8 {
  background: url(gogh8.jpg);
}

.gogh9 {
   background: url(gogh9.jpg);
}

.gogh10 {
   background: url(gogh10.jpg);
}

.highlight {
  font-size: 200px;
}

JavaScript ~ 我正在使用 jQuery 顺便说一句

$(function() {

  $(".button").click(function(){

    let goghs = ["gogh1", "gogh2", "gogh3", "gogh4", 
                "gogh5", "gogh6", "gogh7",  "gogh8",
                "gogh9", "gogh10"]
    let i = Math.floor(Math.random()* goghs.length - Math.random() + 2 );
    $("body").toggleClass(goghs[i]);
  });
});

标签: javascripthtmljquerycss

解决方案


由于您要求 Javascript 帮助。

这是您在代码中遇到的问题:

编辑:

$(function () {

  $(".button").click(function () {

    let goghs = ["gogh1", "gogh2", "gogh3", "gogh4",
      "gogh5", "gogh6", "gogh7", "gogh8",
      "gogh9", "gogh10"
    ]
    let i = Math.floor(Math.random() * goghs.length); //There was no need to add + Random plus 2 to it. You already Selecting a random index from an array(sometimes 'i' value was 10 -> undefined).
    console.log(i, goghs[i]); //logging helps you notice that is nothing wrong with other parts and function runs. only the code itself has some problems.
    $("body").toggleClass(goghs[i]);
  });
});

推荐阅读