jQuery属性操作
1.属性
- attr() 操作所有的属性(自定义和内置的)
- prop() 操作HTML元素内置属性
- removeAttr()
- removeProp() 并不能删除HTML元素上的属性(可以删除通过prop给该元素添加的对象)
2.css类
- addClass() 给元素添加一个class值
- removeClass() 删除一个class值
- toggleClass() 切换一个class值
- hasClass() 判断是否有某个class,返回true和false
小练习:简单的切换功能
div {
width: 100px;
height: 100px;
background: orange;
}
.select {
background-color: red;
}
<div></div>
<hr>
<div></div>
<hr>
<div></div>
<hr>
<div></div>
<hr>
<div></div>
$(document).ready(function() {
$("div").click(function(){
//每当点击下一个div时清除所有div选中的状态
$("div").removeAttr("class");
$(this).toggleClass("select");
})
})
3.HTML代码/文本/值
- html()设置获取元素里面的html代码 类似于innerHTML
- text()内容直接是文本
- val() 设置或 获得表单控件里的值
jQuery样式操作
1.css操作
- css() 可获取可设置
两种方式
$("#box").css("border","5px solid green").css("width","500").css("height","400");
$("#box").css({
"width" : "400px",
"height" : "400px",
"background-color" : "pink"
})
2.位置
- offset() 元素在页面中的坐标,返回的是一个对象
设置位置
$(".box").offset({left:100,top:100});
- position() 元素在第一个定位的祖先元素中的坐标
3.尺寸
- width()/height() 元素内容尺寸
- innerWidth()/innerHeight() 元素内容尺寸+padding
- outerWidth()/outerHeight() 盒子的尺寸