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的基础上演变而来的!!