jQuery样式操作
1.css() 方法
css() 方法返回或设置匹配的元素的一个或多个样式属性。
1.1 设置CSS样式
// 设置一个属性
$("#box").css("background-color", "blue");
// 设置多个属性
$("#box").css({
"color": "red",
"font-size": "30px",
"text-align": "center"
});
1.2 获取CSS样式
jQuery的获取CSS样式,不但可以获取行内样式,还可以获取内部样式和外部样式。
// 获取背景颜色值
console.log($("#box").css("background-color"));
// 获取字体大小值
console.log($("#box").css("font-size"));
2.CSS尺寸
2.1 width() 和 height() 方法
width() 方法设置或返回元素的宽度(不包括内边距、边框或外边距)。
height() 方法设置或返回元素的高度(不包括内边距、边框或外边距)。
// 1.设置宽高
$("div").css({"width" : "200px", "height" : "200px"});
$("div").width(300).height(300);
// 2.获取宽高
console.log($("div").css("width"));
console.log($("div").width());
console.log($("div").css("height"));
console.log($("div").height());
// 3.获取窗口的宽高
console.log("窗口宽度: " + $(window).width());
console.log("窗口高度: " + $(window).height());
// 4.获取文档的宽高
console.log("文档宽度: " + $(document).width());
console.log("文档高度: " + $(document).height());
注意:width/height和CSS的区别是一个带单位,另一个不带单位。
2.2 innerWidth() 和 innerHeight() 方法
innerWidth() 方法返回元素的宽度(包括内边距)。
innerHeight() 方法返回元素的高度(包括内边距)。
// 1.返回元素的宽度(包括内边距)
console.log($("div").innerWidth());
// 2.返回元素的高度(包括内边距)
console.log($("div").innerHeight());
2.3 outerWidth() 和 outerHeight() 方法
outerWidth() 方法返回元素的宽度(包括内边距和边框)。
outerHeight() 方法返回元素的高度(包括内边距和边框)。
// 1.返回元素的宽度(包括内边距和边框)
console.log($("div").outerWidth());
// 2.返回元素的高度(包括内边距和边框)
console.log($("div").outerHeight());
outerWidth(true) 方法返回元素的宽度(包括内边距、边框和外边距)。
outerHeight(true) 方法返回元素的高度(包括内边距、边框和外边距)。
// 1.返回元素的宽度(包括内边距、边框和外边距)
console.log($("div").outerWidth(true));
// 2.返回元素的高度(包括内边距、边框和外边距)
console.log($("div").outerHeight(true));