1、window.getComputedStyle方法
功能:獲取最終應(yīng)用在元素身上的樣式
語法: getComputedStyle("元素", "偽元素"),第二個參數(shù)可選
返回值:元素的樣式對象
IE6-8不支持該屬性,有個對應(yīng)屬性currentStyle。
與style的區(qū)別:style只能拿到元素style屬性中的樣式信息,getComputedStyle可以拿到任意屬性/值的集合,與getPropertyValue配合使用就可以拿到任意屬性值。
Tip:jquery/zepto的css方法拿不到偽元素樣式,但該方法可以??!
2、Element.getBoundingClientRect方法
功能:相對于視口,獲取指定元素size和position
語法:element.getBoundingClientRect()
返回值:包含bottom,height,left,right,top,width,x,y的對象(Chrome下),基準(zhǔn)點是視口左上角。
Tip:當(dāng)Element被display:none后,返回的所有屬性都為0
3、Object.assign方法
語法:Object.assign(target, ...sources),返回target對象,將sources中所有可枚舉屬性賦值到target對象,但是只是淺復(fù)制,即復(fù)制引用,看下列子:
function test() {
'use strict';
let obj1 = { a: 0 , b: { c: 0}};
let obj2 = Object.assign({}, obj1);
console.log(JSON.stringify(obj2)); // { a: 0, b: { c: 0}}
obj1.a = 1;
console.log(JSON.stringify(obj1)); // { a: 1, b: { c: 0}}
console.log(JSON.stringify(obj2)); // { a: 0, b: { c: 0}}
obj2.a = 2;
console.log(JSON.stringify(obj1)); // { a: 1, b: { c: 0}}
console.log(JSON.stringify(obj2)); // { a: 2, b: { c: 0}}
obj2.b.c = 3;
console.log(JSON.stringify(obj1)); // { a: 1, b: { c: 3}}
console.log(JSON.stringify(obj2)); // { a: 2, b: { c: 3}}
// 深度復(fù)制
obj1 = { a: 0 , b: { c: 0}};
let obj3 = JSON.parse(JSON.stringify(obj1));
obj1.a = 4;
obj1.b.c = 4;
console.log(JSON.stringify(obj3)); // { a: 0, b: { c: 0}}
}
test();
注意:Object.assign()方法是淺復(fù)制,使用時要注意這點
4、scrollIntoView & scrollIntoViewIfNeed
- scrollIntoView(param)
<body>
<div class="chunk"></div>
<div class="btn">click</div>
<script>
const btn = document.querySelector('.btn');
const test = document.querySelector('.chunk');
btn.addEventListener('click', function() {
test.scrollIntoView();
})
</script>
</body>
param可取boolean和object,當(dāng)為Boolean時,取true(默認(rèn)值)與可視區(qū)域頂部對齊;當(dāng)object時,可設(shè)置兩個key,一個block,取值為start/end,功能類似于取Boolean,另一個behavior,取值instant(auto)/smooth;兼容性有限!
- scrollIntoViewIfNeed
scrollIntoViewIfNeeded是比較懶散的,如果元素在可視區(qū)域,那么調(diào)用它的時候,頁面是不會發(fā)生滾動的。其次是scrollIntoViewIfNeeded只有Boolean型參數(shù),也就是說,都是瞬間滾動