加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 资源网站 > 资源 > 正文

使用JavaScript在类之间切换

发布时间:2020-12-14 23:20:26 所属栏目:资源 来源:网络整理
导读:我有以下代码. HTML在下面. 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);}

我有以下代码.

HTML在下面.

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”).请注意.在classname前面(它是一个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/

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读