gpt4 book ai didi

javascript - 如何通过单击 HTML 按钮来隐藏和显示图像

转载 作者:搜寻专家 更新时间:2023-10-31 08:50:42 24 4
gpt4 key购买 nike

当我点击任何字母按钮时,我试图根据字母字符更改图像。

HTML

<div id="btn">
<input type="button" onclick="hideImage();" value="A" class="btn-group" />
</div>

<div id="images">
<img src="Letter-A.png" class="image-group"></img>
</div>

JavaScript

 function hideImage() {
var button = document.getElementsByClassName("btn-group");
document.getElementsByClassName('image-group').onclick = function() {
if (button.style.display == "none") {
button.style.display = "block";
} else {
button.style.display = "none";
}

我收到错误“显示”属性无法设置为未定义。

最佳答案

getElementsByClassName() gathers all elements with a given className这叫做 HTMLCollection or NodeList .为了引用 NodeList/HTMLCollection 中的每个元素,我们必须使用 for 循环遍历每个元素,或者将 NodeList 转换为数组然后使用数组方法在上面。

下面的 Demo 使用了后者(一个数组方法);

  • Array.from()将每个 NodeList 转换成数组

  • forEach() 数组方法遍历数组并在每个 button.btn 上分配一个 onclick 事件处理程序将每个事件处理程序/button.btn 关联到相应的 img.img 根据数组的当前索引位置。

  • 每个图像的实际显示/隐藏行为由 classList.toggle('off') 提供

演示

Demo中有详细说明


/* Collect all .btn classes into a NodeList and comvert it into 
|| an array
*/
var btnGroup = Array.from(document.getElementsByClassName("btn"));

/* Collect all .img classes into a NodeList and convert it into
|| an array
*/
var imgGroup = Array.from(document.getElementsByClassName('img'));

/* Iterate (loop) thru the imgGroup array with forEach() array
|| method.
*/// In each loop get a .btn from the btnGroup array's index
//// position that corresponds with the current index of the loop.
//// Register an onclick event handler that toggles the .off class
//// to a .img of the imgGroup array positioned at current loop
//// index.


imgGroup.forEach(function(img, idx) {

btnGroup[idx].onclick = function() {

img.classList.toggle('off');
}

});
.off {
display: none;
}
<div id="btn-group">
<input type="button" value="A" class="btn" />
<input type="button" value="B" class="btn" />
<input type="button" value="C" class="btn" />
<input type="button" value="D" class="btn" />
<input type="button" value="E" class="btn" />
</div>

<div id="img-group">
<img src="https://www.luckyclovertrading.com/images/LBL14CG_A_a.jpg" class="img" width='100'>

<img src="https://etc.usf.edu/presentations/extras/letters/theme_alphabets/26/12/B-400.png" class="img" width='100'>

<img src="https://etc.usf.edu/presentations/extras/letters/fridge_magnets/orange/13/C-400.png" class="img" width='100'>

<img src="https://etc.usf.edu/presentations/extras/letters/varsity_letters/37/16/D-400.png" class="img" width='100'>

<img src="https://images-na.ssl-images-amazon.com/images/I/31ETtJ6FG6L.jpg" class="img" width='100'>
</div>

关于javascript - 如何通过单击 HTML 按钮来隐藏和显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50557647/

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