这是代码:
let selected_animal = "Animals"
// Hover Function
$("#cats_image").mouseover(function() {
$("h1").text("Cats");
});
$("#dogs_image").mouseover(function() {
$("h1").text("Dogs");
});
$("#ducks_image").mouseover(function() {
$("h1").text("Ducks");
});
$("img").mouseout(function() {
$("h1").text(selected_animal);
});
// Click Function
$("#cats_image").click(function() {
selected_animal = "Cats"
$("h1").text("Cats");
$("footer div").removeClass("show");
$("#cats_text").addClass("show");
});
$("#dogs_image").click(function() {
selected_animal = "Dogs"
$("h1").text("Dogs");
$("footer div").removeClass("show");
$("#dogs_text").addClass("show");
});
$("#ducks_image").click(function() {
selected_animal = "Ducks"
$("h1").text("Ducks");
$("footer div").removeClass("show");
$("#ducks_text").addClass("show");
});
// White Area Click Function
$("body").click(function() {
event.stopPropagation();
// ???
});
* {
margin: 0;
padding: 0;
font-family: sans-serif;
font-weight: normal;
}
header {
width: 100%;
}
img {
max-width: 200px;
cursor: pointer;
}
footer div {
display: none;
}
.show {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<header>
<h1>Animals</h1>
</header>
<main>
<img id="cats_image" src="https://upload.wikimedia.org/wikipedia/commons/c/c4/Mackerel_tabby_cat_pair-Hisashi-01.jpg">
<img id="dogs_image" src="https://upload.wikimedia.org/wikipedia/commons/7/76/Two_puppies_dogs.jpg">
<img id="ducks_image" src="https://upload.wikimedia.org/wikipedia/commons/c/c8/The_pair_of_ducks.jpg">
</main>
<footer>
<div id="cats_text">Domestic cats are valued by humans for companionship and their ability to hunt rodents.</div>
<div id="dogs_text">The coats of domestic dogs are of two varieties: "double" being familiar with dogs (as well as wolves) originating from colder climates, made up of a coarse guard.</div>
<div id="ducks_text">Duck is the common name for numerous species in the waterfowl family Anatidae which also includes swans and geese.</div>
</footer>
一切正常,应该如何工作。但是,如果您现在单击白色区域中的某个位置(没有文本,也没有图像),则应该恢复初始状态。就是说,不应有页脚文本,而h1应该是“动物”。如何做到这一点?
非常感谢您的帮助!:)
您可以将return false;
语句添加到每个img的所有单击事件声明中。而且您的body事件将只更改文本并删除Class,如下所示:
$("body").click(function() {
selected_animal = "Animals";
$("h1").text(selected_animal);
$("footer div").removeClass("show");
});
其他声明应如下所示:
$("#ducks_image").click(function() {
selected_animal = "Ducks"
$("h1").text("Ducks");
$("footer div").removeClass("show");
$("#ducks_text").addClass("show");
return false;//here is the return statement
});
在false
实际上并没有让事件传播高达html
标签。因此,如果img
单击,则body
不会单击,body
也不会触发事件。仅在白色区域中单击时才会触发。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句