2. CSS & Style
优质
小牛编辑
135浏览
2023-12-01
CSS & Style
2.1 CSS
Get style
// jQuery
$el.css("color");
// Native
// 注意:此处为了解决当 style 值为 auto 时,返回 auto 的问题
const win = el.ownerDocument.defaultView;
// null 的意思是不返回伪类元素
win.getComputedStyle(el, null).color;
Set style
// jQuery
$el.css({ color: "#ff0011" });
// Native
el.style.color = '#ff0011';
Get/Set Styles
注意,如果想一次设置多个 style,可以参考 oui-dom-utils 中 setStyles 方法
Add class
// jQuery
$el.addClass(className);
// Native
el.classList.add(className);
Remove class
// jQuery
$el.removeClass(className);
// Native
el.classList.remove(className);
has class
// jQuery
$el.hasClass(className);
// Native
el.classList.contains(className);
Toggle class
// jQuery
$el.toggleClass(className);
// Native
el.classList.toggle(className);
2.2 Width & Height
Width 与 Height 获取方法相同,下面以 Height 为例:
Window height
// window height
$(window).height();
// 含 scrollbar
window.document.documentElement.clientHeight;
// 不含 scrollbar,与 jQuery 行为一致
window.innerHeight;
Document height
// jQuery
$(document).height();
// Native
const body = document.body;
const html = document.documentElement;
const height = Math.max(
body.offsetHeight,
body.scrollHeight,
html.clientHeight,
html.offsetHeight,
html.scrollHeight
);
Element height
// jQuery
$el.height();
// Native
function getHeight(el) {
const styles = this.getComputedStyle(el);
const height = el.offsetHeight;
const borderTopWidth = parseFloat(styles.borderTopWidth);
const borderBottomWidth = parseFloat(styles.borderBottomWidth);
const paddingTop = parseFloat(styles.paddingTop);
const paddingBottom = parseFloat(styles.paddingBottom);
return height - borderBottomWidth - borderTopWidth - paddingTop - paddingBottom;
}
// 精确到整数(border-box 时为 height - border 值,content-box 时为 height + padding 值)
el.clientHeight;
// 精确到小数(border-box 时为 height 值,content-box 时为 height + padding + border 值)
el.getBoundingClientRect().height;
2.3 Position & Offset
Position
获得匹配元素相对父元素的偏移
// jQuery
$el.position();
// Native
{ left: el.offsetLeft, top: el.offsetTop }
Offset
获得匹配元素相对文档的偏移
// jQuery
$el.offset();
// Native
function getOffset (el) {
const box = el.getBoundingClientRect();
return {
top: box.top + window.pageYOffset - document.documentElement.clientTop,
left: box.left + window.pageXOffset - document.documentElement.clientLeft
}
}
2.4 Scroll Top
获取元素滚动条垂直位置。
// jQuery
$(window).scrollTop();
// Native
(document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop;