操作DOM样式
CSS属性
获取CSS属性值
$("E").css("属性")
设置CSS属性值
$("E").css("属性1","属性值1")
$("E").css({"属性1":"属性值1"})
$("E").css({"属性1":"属性值1","属性2":"属性值2",……})
CSS类名操作
添加类名
在jQuery中,可以使用addClass()方法为元素添加类名。
$("E").addClass("类名")
删除类名
$("E").removeClass("类名")
<head>
<title></title>
<style type="text/css">
.myLi
{
color:Red;
background-color:#F1F1F1;
font-weight:bold;
}
</style>
<script src="jquery-1.12.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$("#add").click(function () {
$("ul li:nth-child(odd)").addClass("myLi");
});
$("#remove").click(function () {
$("ul li:nth-child(odd)").removeClass("myLi");
});
})
</script>
</head>
<body>
<ul>
<li>HTML</li>
<li>CSS</li>
<li>JavaScript</li>
<li>jQuery</li>
<li>vue</li>
</ul>
<input id="add" type="button" value="添加" />
<input id="remove" type="button" value="删除" />
</body>
切换类名
$("E").toggleClass("类名")
使用toggleClass()方法来切换类名,使得元素可以在“默认样式”以及“class样式”之间来回切换。
元素宽高及位置
元素宽高
$().width() //获取元素的宽度
$().width(n) //设置元素的宽度,n是一个整数,表示npx
$().height() //获取元素的高度
$().height(n) //设置元素的高度,n是一个整数,表示npx
和$().css("width/height");
之间的区别在于获得的宽度/高度值不带单位(仅仅是数字),而css("width/height")获取的宽度值带“px”作为单位。
元素位置
$("E").offset().top;
$("E").offset().left;
使用offset()方法用于“获取”或“设置”元素相对于“当前文档”(也就是浏览器窗口)的偏移距离。
$("E").position().top;
$("E").position().left;
使用position()方法用于“获取”或“设置”当前元素相对于其父元素的偏移距离。