在学习jQuery过程当中,我总结出css方法一些须要注意的点和新的知识须要学习的知识;css
设置时,如宽高字体大小等,能够直接写数值型,默认单位为px;数组
$("div").css("width",50);
$("div").css("width","50px");
$("div").css("width",function(index,item){ // item是当前元素的宽度 return 50*(index+1); })
jQuery中css方法第二个参数能够是回调函数,返回的值至关于设置的值;dom
函数的两个参数第一个表明当前元素的索引值,第二个表明当前设置的样式;函数
上面代码表示:设置div元素的宽度以50px叠加;学习
1 $("div").css({ 2 width:50, 3 height:function(index){ 4 return (index+1)*50; 5 }, 6 backgroundColor:function(){ 7 //返回随机颜色 8 return "#"+Math.floor(Math.random()*0x1000000).toString(16).padStart(6,"0"); 9 } 10 });
css方法能够接收一个函数,设置多个样式;字体
上面代码表示:将div元素的宽设置为50px,高设置以50px叠加,而且把每个div的背景色设置为随机颜色;spa
console.log($("div").css("height"));
只能获取到匹配到的第一个元素样式的值,而且该值为字符串类型;code
上面代码表示:获取第一个div元素的高度,返回一个带px的字符串类型的值;对象
console.log($("div").css(["width","height","backgroundColor"]))
css方法能够接收一个数组,而且遍历该数组的全部样式;blog
上面代码表示:获取第一个div的宽高和背景色属性值;
能够使用数组遍历的方法
1 var arr=[]; 2 $("div").css("height",function(index,item){ 3 arr.push(item); 4 }); 5 console.log(arr);
上面代码表示:把遍历全部匹配到的div,而且把属性值追加到数组中,打印数组。
1 var arr=[]; 2 $("div").each(function(){ 3 arr.push({}); 4 }).css({ 5 width:function(index,item){ 6 arr[index].width=item; 7 }, 8 height:function(index,item){ 9 arr[index].height=item; 10 }, 11 backgroundColor:function(index,item){ 12 arr[index].backgroundColor=item; 13 } 14 }) 15 console.log(arr);
上面代码表示:遍历全部的div元素,而且在arr数组中添加一个空对象,把获取的宽高和背景色当作键值对填入到对象中,而且打印数组,获得全部div指定的多个样式。
index表示全部div的索引值,item表示该样式的值;
总结: