jQuery中的样式操作

                                             jQuery中的class样式操作

一。jQuery与JavaScript的class样式属性添加和移除:

<head>
    <meta name="viewport" content="width=device-width" />
    <title>text</title>
    <style>
        .wrapper{
            width:200px;
            height:200px;
            background-color:red;
        }
    </style>
</head>
<body>
    <div id="box"> 
    </div>
    <script src="~/Content/js/jquery-3.2.1.min.js"></script>
    <script>
        //js
        //获取元素
        var box = document.getElementById("box");
        //给box添加class属性与属性值
        box.setAttribute("class", "wrapper");
        //获取box元素的class属性值
        var str = box.getAttribute("class");
        //输出/结果
        console.log(str);
        //移除box元素的id属性
        box.removeAttribute("id");

        //jQuery
        //attr 添加属性
        $("#box").attr("index", "12");
        var index = $("#box").attr("index");
        console.log(index);

        //removeAttr  移除
        //$("#box").removeAttr("index");
    </script>
</body>

上面就是jQuery与JavaScript的属性添加和移除,我都给基每段加上对应基本的意思,方便更好理解;

在JavaScript中:setAttribute()   添加属性      removeAttribute ()  移除

在jQuery中: attr()   添加属性      removeAttr()  移除

 

二。对class类的操作

代码如下:

<body>
    <div id="box" class="box"> 
    </div>
    <button id="btn">class切换</button>  
    <script src="~/Content/js/jquery-3.2.1.min.js"></script>
    <script>
        //js
          var box = document.getElementById("box");
        // box.className = "wrapper";  相当于重置某个值
        //box。classList 操作某个类      add 添加某个类
       // box.classList.add("wrappe");
        //remove   移除
       // box.classList.remove("box");

        //jq
        //addClass 添加某个类
      //  $("#box").addClass("wrapper");
        //removeClass  移除
        //$("#box").removeClass("box");

        $("#btn").click(function () {//回调函数
            // toggleClass()  切换
            $("#box").toggleClass("wrapper");
            //判断box是否有wrapper这个类
            var bl = $("#box").hasClass("wrapper");
            console.log(bl);
        })
    </script>
</body>

 上面分别就是jQuery与JavaScript对class类的操作,我给某些单词加上相应的意思,方便更好理解;

不过同一个意思的单词在JavaScript与jQuery上的写法都不一样

如,在JavaScript中: remove   移除       add 添加某个类

而在jQuery中:removeClass  移除           addClass 添加某个类

总结:相对JavaScript来说,jQuery的写法相对于简单,不过jQuery好像是在JavaScript的基础上演变而来的!!

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值