jQuery的css样式设置和获取
jquery中没有style属性,css通过.css()设置,不但可以获取行内样式的值,也可以获取css设置的计算后样式,相当于js中getcomputedStyle
- css()的参数可以是两个,第二个是回调函数
$("div").css("width",50); //不用加px
$("div").css("width", function (index, item) { //设置不同的样式
return (index + 1) * 50;
})
console.log($("div").css("width")); //获取计算后的样式
2.css多个样式的设置 css()的参数可以是个对象
$("div").css({
function (index, item) {
return (index + 1) * 50;
},
height: function (index, item) {
return (index + 1) * 50;
},
backgroundColor: function (index, item) {
var color = "#";
for (var i = 0; i < 6; i++) {
color += Math.floor(Math.random() * 16).toString(16);
}
return color;
},
border: "1px solid #000000"
});
3.css的样式可以是个数组 用来获取第一个元素的指定样式值,返回一个对象
console.log($("div").css(["width","height","backgroundColor"]));
4.添加和删除className
$("div").addClass("div1");
$("div").addClass("div1 div2");
$("div").removeClass("div1");
$("div").removeClass("div1 div2");
5.设置css样式,通过对className的添加删除,达到元素样式的控制(和vue的方法相同,实现响应式布局)
var bool = false;
$("div").on("click", function () {
bool = !bool;
if (bool) $(this).removeClass("div1").addClass("div2");
else $(this).removeClass("div2").addClass("div1");
})
//简单写法
$("div").on("click",function(){
$(this).toggleClass("div2"); //点击删除div2,再次点击添加div2,覆盖之前的calssName
})
6.宽高的获取和设置
$("div").width() //内容宽度width
//内容宽高的设置
$("div").width(100).height(100);
$("div").innerWidth() //width+padding 相当于js中的div.clientWidth
$("div").innerWidth(100); //80 有20px的padding
$("div").outerWidth() //width+padding+border 相当于js中的div.offsetWidth
$("div").outerWidth(100);//76 有20px的padding和4px的border
$("div").outerWidth(true) ///width+padding+border+margin
//只能获取,不能设置
$(".div3").offset() //元素相对页面左上角的位置 相当于js中的div.offsetleft/offsetTop
$(".div3").offset({left:500,top:500}); //元素位置的设置
console.log($(".div3").position()) //得到的是定位位置
//只能获取,不能修改
console.log($(".div2").scrollTop());
console.log($(".div2").scrollTop(1000));
//获取和设置滚动条位置