gpt4 book ai didi

JavaScript "classList"切换不切换元素的类名

转载 作者:行者123 更新时间:2023-11-30 19:54:15 24 4
gpt4 key购买 nike

我正在努力提高我的 JavaScript 技能,但我无法解决这个问题。我想在 button.terug 时在我的 body 中显示图像被点击。

我尝试使用 classList.toggle()切换类名 popup来自 <img>单击元素,但它似乎不起作用。我做错了什么?

JS:

var uno = document.querySelector('button.terug');

var popup = document.querySelector('img.popup');

uno.addEventListener ('click', function(){
popup.classList.toggle('img.popup');
});

HTML:

<button class="terug"></button>
<img class="popup" src="images/popup1.png" alt="beoordeling">

最佳答案

您正在尝试在 .popup 元素类列表中切换类名 img.popup切换类名 popup

改变这个:

uno.addEventListener ('click', function(){
popup.classList.toggle('img.popup');
});

对此:

uno.addEventListener ('click', function(){
popup.classList.toggle('popup'); // you don't need to add the dot since classList knows that the argument is a reference to a class-name.
});

检查并运行下面的代码片段以获得上述代码的实际示例:

/* JavaScript */

var uno = document.querySelector(".terug");
var popup = document.querySelector(".popup");

uno.addEventListener ('click', function(){
popup.classList.toggle('popup'); // you don't need to add the dot since classList knows that the argument is a reference to a class-name.
});
/* CSS */

img {opacity: 0;}
img.popup {opacity: 1;}
<!-- HTML -->

<button class="terug">Click Me</button>
<img class="popup" src="images/popup1.png" alt="beoordeling">

关于JavaScript "classList"切换不切换元素的类名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54188174/

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