//添加属性
$("div").attr("names","li");
//获取属性
$("div").attr("names");
$("div").attr("names",function (index,value) {
return "li"+index;
})
//这样就给每个div都根据他的index值设置了不同的names属性
$("div").attr({
"names":function (index,value) {
return "li"+index;
},
"toggle-data":function (index) {
return "data"+index;
}
})
//总结:
$("选择器").attr({
"属性1":function(index,value){
return 值;
},
"属性2":function(index,value){
return 值;
}
})
添加样式:
$("div").css("backgroundColor","red");
获取样式:
$("div").css("backgroundColor")
还可以添加多个样式:
$("div").css({
"width":"100px",
height:"100px"
})
$("div").css({
"width":function (index) {
return (index+1)*20+"px"
},
height:function (index) {
return (index+1)*20+"px"
},
backgroundColor:function (index) {
return "#"+(Math.floor(Math.random()*256*256*256)).toString(16)
}
})
通过function的方法,给同一个样式设置不同个的值
当添加多个样式的时候可以使用空格分开
$("div").addClass("div0 div2");
可以移除其中的任意一个样式
$("div").removeClass("div2");
这里括号里的样式是样式表中定义的样式,不是标签样式
taggleClass()可以切换样式,但是是样式表里的样式
$("div").addClass("div0").on("click",function (e) {
// 这里的this是被点击的DOM对象
// console.log(this);
$(this).toggleClass("div1");
})
括号里面是true,切一次
$(this).toggleClass("div1",true);
括号里面是false,不可切换
$(this).toggleClass("div1",false);
设置的,不用加单数,会自动加上
$("div").width(100);
$("div").height(100);
获取宽度纯数字,也不带单位
console.log($("div").width())
console.log($("div").height())
获取宽和padding值
$("div").innerWidth();//width+padding
$("div").innerWidth(100);//其实可以设置,尽量不要设置这个宽高,因为内容加padding会影响布局
outWidth是在上面的基础上再多加一个border的值
$("div").outerWidth();//width+padding+border;
整个是在括号中填true,表示再多加上margin的值
$("div").outerWidth(true);//width+padding+border+margin
仅获取,不可设置
console.log($("div").offset().left);//{left,top};
let {left,top}=$("div").offset();
console.log(left,top);
position相对于父元素定位的位置,offset是相对于页面的位置
console.log($(".div1").position());
console.log($(".div1").offset());