javascript - 按钮单击以提供随机图像背景(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]);
});
});
解决方案
由于您要求 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]);
});
});
推荐阅读
- c# - winforms - 两次显示相同的表格?
- javascript - 从 Gmail 获取电子邮件详细信息并保存到 Mysql 数据库
- python - 如何在 Tensorflow 中解析音频 Wav 文件
- android - 如何在应用程序被终止时处理 fcm 推送通知,而不使用 WakefulBroadcastReceiver 作为其在 26.1.0 中已弃用的?
- java - 如何从本地应用程序连接到远程配置单元?
- dart - 如何在 Flutter 中播放在线广播?
- c++ - 使用 winsock 库发送 GET http 请求时出现 400 bad request 错误
- c - 转换 C 和汇编
- react-native - 使用Realm与现有应用进行ReactNative集成,ReactNative的页面无法正常加载
- opencv - 在 Windows Server 2012 R2 中使用 OpenCV 的 Canny 函数时 C++ 崩溃