js插件jquery可以很方便的对HTML的元素进行操作,比如一些元素的显示与隐藏,一些元素的动态效果等,今天就说一说通过jquery获取DIV元素的CSS属性,以及设置DIV元素的CSS属性的方法。
jquery获取DIV元素的CSS属性值
jq获取DIV元素的属性值,可以使用css()方法
例:利用jquery获取DIV元素的宽
<!DOCTYPE html>
<html>
<head>
<title>Document</title>
<style>
#mochu{
margin: 10px;
padding: 10px;
color: red;
height: 30px;
width: 40px;
}
</style>
<script src="https://cdn.staticfile.org/jquery/2.2.4/jquery.min.js"></script>
</head>
<body>
<div id="mochu">飞鸟慕鱼博客<br/>http://www.feiniaomy.com</div>
<script>
var h = $('#mochu').css('width');
console.log(h);
</script>
</body>
</html>
打印结果:
40px
例:利用jquery获取DIV元素的高
<!DOCTYPE html>
<html>
<head>
<title>Document</title>
<script src="https://cdn.staticfile.org/jquery/2.2.4/jquery.min.js"></script>
</head>
<body>
<div id="mochu">飞鸟慕鱼博客<br/>http://www.feiniaomy.com</div>
<script>
var h = $('#mochu').css('height');
console.log(h);
</script>
</body>
</html>
打印结果:
42px
注意:
1、如果给DIV元素定义了CSS属性的值,则直接输出定义的CSS值
2、如果未定义DIV元素的CSS属性值,则输出浏览器渲染后DIV的默认值
利用jquery设置DIV元素的值
在JQ中可以通过CSS方法获取DIV元素的CSS属性值,也可以设置或改变元素的CSS属性值
例:利用jq改变字体的颜色
<!DOCTYPE html>
<html>
<head>
<title>Document</title>
<script src="https://cdn.staticfile.org/jquery/2.2.4/jquery.min.js"></script>
</head>
<body>
<div id="mochu">飞鸟慕鱼博客<br/>http://www.feiniaomy.com</div>
<script>
$('#mochu').css('color','red');
</script>
</body>
</html>
结果如图:


注:改变DIV中字体的颜色其实就是给这个DIV加入了一个 color 的CSS属性,并把属性值设置成 red(红色)
在浏览器中查看元素就可以发现加入的CSS属性


例:给DIV元素加入多个CSS属性
<!DOCTYPE html>
<html>
<head>
<title>Document</title>
<script src="https://cdn.staticfile.org/jquery/2.2.4/jquery.min.js"></script>
</head>
<body>
<div id="mochu">飞鸟慕鱼博客<br/>http://www.feiniaomy.com</div>
<script>
$('#mochu').css({'color':'red','heigth':'40px','width':'40px'});
</script>
</body>
</html>
在浏览器中审核元素,如下图


可以发现,对过JQ设置的CSS属性都写到了DIV上
注意:利用JQ的CSS()方法设置或添加多个CSS属性的时候,要以{”:”,”:”}这种数据格式写入。
