jQuery 学习笔记 CSS, Styling, & Dimensions
jQuery可以处理CSS的属性,包括两种方法
一是通过.CSS()方法来获取和设置属性,这和其他的方法一样,需要注意的是设置属性时的两种形式
- fontSize
- font-size
一般在js代码中采用第一种形式
二是通过向元素添加一个具体的CSS类,这样就不需要在js代码中写css了,主要通过以下方法:
- addClass()
- removeClass()
- toggleClass()
- hasClass()
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>CSS Demo</title> <style type="text/css"> h1 { background-color: red; font-size: 50px; } .div1 { background-color: blue; width: 100px; height: 50px; } .div2 { background-color: yellow; width: 80px; height: 40px; } </style> </head> <body> <h1>Hello World!</h1> <div> <span>jQuery</span> </div> <script type="text/javascript" src="jquery-1.10.2.min.js"></script> <script type="text/javascript"> console.log($("h1").css("backgroundColor")); $("h1").css("fontSize","100px"); $("h1").css({ fontSize:"80px", backgroundColor:"yellow" }); var $div1 = $("div"); $div1.addClass('div1'); setTimeout(function(){ $div1.removeClass('div1') },2000); setTimeout(function(){ $div1.addClass('div2') },2000); </script> </body> </html>
最后就是处理形状大小的方法,经常使用的有:
- height()
- width()
- position()