規范
<style type="text/css"></style>
<script type="text/javascript"></script>
讀寫樣式屬性
.style
是訪問不到css樣式表的,只能訪問到行內/內聯的屬性,當未設置行內屬性時,結果為空字符串
- 設置時,對復合值需要拆解賦值,不拆解效率更低
oDiv.style.weight='200px';
oDiv.style.border='5px solid #000';
// 更合適的寫法如下,拆解
oDiv.style.borderWidth='5px';
oDiv.style.borderStyle='solid';
oDiv.style.borderColor='#000';
- 設置float要寫成cssFloat(雖然設置float也有效果但是不規范,float是css中的保留字,也有浮點的含義)
查看元素css屬性
1. 元素.style
對于不同的盒子模型是什么
- 當給元素設置了行內樣式時
- 當元素未設置內聯樣式時
2. window.getComputedStyle(elem,null)
- 查看計算樣式
- 返回值是類數組
- 屬性是只讀的
- 是絕對值(非數學意義上的絕對值):em、rem轉換為px,十六進制轉換為rgb
- IE8及以下不支持
Failed to set the ‘background’ property on ‘CSSStyleDeclaration’: These styles are computed, and therefore the ‘background’ property is read-only.
at HTMLDivElement.oDiv.onclick
-
獲取元素行內、css樣式表
-
.style和getComputedStyle的區別
-
IE8支持
elem.currentStyle
-
該方法獲取到的height是否是盒子的實際高度,是由盒子模型決定的
-
【兼容】
function getStyles(elem, prop) {if (window.getComputedStyle) {if (prop) {return window.getComputedStyle(elem, null)[prop];} else {return window.getComputedStyle(elem, null);}} else {if (prop) {return elem.currentStyle[prop];} else {return elem.currentStyle;}}
}
3.offsetWidth/offsetHeight
- 訪問元素的實際寬高
- 包含元素的padding、border(box-sizing為content-box時)
- 會在元素渲染后訪問(即使設置的是css樣式表也能)
- box-sizing為content-box時,長大的速度更快,因為始終獲得都是真實寬高,起始的基數不一樣
- 在js運動中的問題,如果設置的是css樣式表
box-sizing為content-box時
- 使用
box-sizing:border-box;
,初始的盒子變小了
box-sizing為content-box時
操作偽元素
- 操作偽元素最好的方法就是使用類名控制
- window.getComputedStyle(elem,null)第二個參數傳值可以獲取after元素的只讀屬性
下拉選組件動畫
- 要點,每次觸發時需要先清空定時器,否則出現抖動(當mouseenter時未完全展開就mouseleave,enter的定時器還在執行,就開始了leave的定時器)