gpt4 book ai didi

jquery - 如何避免重复大量代码并将相同的规则应用于多个类

转载 作者:行者123 更新时间:2023-12-01 06:25:56 25 4
gpt4 key购买 nike

例如,我有 12 个图像,在单击图像时我想隐藏其他 11 个图像并将单击的图像增加到全屏

我正在尝试找出是否有一种更简单、更直接的方法来实现这一点,而不是沿着

编写大量代码
$('.image_one').click(function() {
$('.image_one').addClass('increase_size');
$('.image_two').hide(); ...etc for the other 11 images
});

所有图像均为 x 12

我对 jQuery 和 Javascript 的了解还算初级,所以我希望有人能够提出一些建议来简化我想要实现的目标

不要求别人为我写出这段代码,只是为我指明大致方向

最佳答案

您可以使用下面的代码。基本上,当用户单击图像时,所有图像都会被隐藏。然后将显示单击的图像,并将该类添加到其中。

$(document).ready(function() {

// User clicks on one of the images
$(".image").click(function() {
// Hide all the images
$(".image").hide();

// Show the image that the user clicks on
$(this).show();

// Add the class to the image the user clicks on
$(this).addClass("increase_size");
});

});
.increase_size{
/* your styles */
}

/* Styles to make the image look like box, you won't need this */

img {
width: 100px;
height: 100px;
}


/* note, the id's are just to add backgorund to each color, don't need this either. */

#image1 {
background-color: red;
}

#image2 {
background-color: green;
}

#image3 {
background-color: black;
}

#image4 {
background-color: grey;
}
<!DOCTYPE HTML>
<html>

<head>
<title>Test Webpage</title>
</head>

<body>
<img src="image1.jpg" class="image" id="image1">
<img src="image2.jpg" class="image" id="image2">
<img src="image3.jpg" class="image" id="image3">
<img src="image4.jpg" class="image" id="image4">

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</body>

</html>
你看……很简单。希望这可以帮助。快乐编码:)

关于jquery - 如何避免重复大量代码并将相同的规则应用于多个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59805812/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com