我正在尝试编写代码,在单击按钮时显示新图片(从海滩图片到湖泊图片)。目前它有点工作,但第一次点击时两张图片都出现了,第二次点击时海滩图片消失了。
这是我目前所拥有的:
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="css/bootstrap.css">
<link rel="stylesheet" href="css/styles.css" type="text/css" media="all">
<script src="js/jquery-3.3.1.js"></script>
<script src="js/scripts.js"></script>
<title>Beach Photo </title>
</head>
<body>
<h1>Photo of Beach </h1>
<h4>Click button below to see a photo of a beach</h4>
<br>
<div class="container">
<form id="show">
<button type="submit" class="btn btn-primary btn-margin">Show</button>
<br>
</form>
<br>
<div id="img">
</div>
<div class="image1">
<img src="img/beach-pic.jpg" alt="photo of beach" id="img1">
<img src="img/lake-pic.jpg" alt="photo of lake" id="img2">
</div>
</div>
</body>
</html>
JQuery:
$(document).ready(function(){
$("form#show").submit(function(){
event.preventDefault();
$("#img1").toggle();
$("#img2").show();
});
});
CSS:
#img1 {
display: none;
}
#img2 {
display: none;
}
最佳答案
在显示或隐藏第二张图片之前,只需检查第一张图片是否显示。您可以尝试以下操作:
$(document).ready(function(){
$("form#show").submit(function(){
event.preventDefault();
$("#img1").toggle();
if($("#img1").is(':visible'))
$("#img2").hide();
else
$("#img2").show();
});
});
#img1 {
display: none;
}
#img2 {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Photo of Beach </h1>
<h4>Click button below to see a photo of a beach</h4>
<br>
<div class="container">
<form id="show">
<button type="submit" class="btn btn-primary btn-margin">Show</button>
<br>
</form>
<br>
<div id="img">
</div>
<div class="image1">
<img src="img/beach-pic.jpg" alt="photo of beach" id="img1">
<img src="img/lake-pic.jpg" alt="photo of lake" id="img2">
</div>
</div>
关于javascript - 单击按钮时更改图片JQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51452729/