gpt4 book ai didi

javascript - 使用 JavaScript 在类之间切换

转载 作者:太空狗 更新时间:2023-10-29 15:32:15 26 4
gpt4 key购买 nike

我有以下代码。

HTML 如下。

<div class="normal">
<p>This is Paragraph No.1</p>
<p>This is Paragraph No.2</p>
<p>This is Paragraph No.3</p>
<p>This is Paragraph No.4</p>
<p>This is Paragraph No.5</p>
</div>

CSS 在下面

.normal {
color: #808080;
border: 4px solid blue;
border-radius: 50px 50px;
width: 800px;
font-family: 'Comic Sans MS';
margin: auto;
margin-top: 10px;
font-size: 30px;
-webkit-transform: rotate(10deg);
}

.change {
color:#ffd800;
border: 6px solid orange;
border-radius: 50px 50px;
width: 800px;
font-family: 'Comic Sans MS';
margin: auto;
margin-top: 10px;
font-size: 30px;
-webkit-transform: rotate(20deg);
}

我想要的是在我单击 div 元素内部时在正常和更改之间切换我的 div 类。我知道如何使用 jQuery 来实现,但我想使用纯 javascript?

以下是我的尝试

(function () {
var pElement = document.getElementsByClassName("normal");
pElement.onclick = function () {
//what to do here
};
} ());

最佳答案

getElementsByClassName 返回一个元素列表,而不是单个元素。所以你会想要从中获取第一个元素,它实际上指的是你的 div。代码应如下所示:

var pElements = document.getElementsByClassName("normal");
var pElement = pElements[0];
pElement.onclick = function () {
if (this.getAttribute("class") == "normal")
this.setAttribute("class", "change")
else
this.setAttribute("class", "normal");
};

演示:http://jsfiddle.net/2QqU5/

如 RobG 所述,仍在使用的旧浏览器不支持 document.getElementsByClassName()。这主要是IE8及以下版本。作为替代方法,您可以使用 document.querySelectorAll(".normal")。注意类名前面的 .(它是一个 CSS 选择器)。由于您只需要一个元素,您还可以使用 document.querySelector(".normal") 来获取那个元素。这实际上可能更容易,因为这些也是 jQuery 使用的选择器,所以在原生和 jQuery 之间来回切换可能更容易。

并且您可以使用 className 属性设置类,而不是使用 get/setAttribute。

将所有这些放在一起,更新后的代码如下所示:

var pElement = document.querySelector(".normal");
pElement.onclick = function () {
if (this.className == "normal")
this.className = "change";
else
this.className = "normal";
};

更新演示:http://jsfiddle.net/2QqU5/2/

关于javascript - 使用 JavaScript 在类之间切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23618210/

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