这是我的代码。我是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 btw
$(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]);
});
});
如果"i〃;第一次是2;gogh2";被添加为类。
如果";i〃;是3,第二次大约是"0";gogh3";将被"添加"到类列表中"gogh2";仍然会在那里。
然后,如果";i〃;第三次是2左右,则它将删除"0";gogh2";而你只剩下";gogh3";。
尝试:
$("body").removeClass();
$("body").addClass(goghs[i]);
取消toggleClass行。
toggleClass将在类不存在的情况下将其添加到列表中,如果存在则将其删除。