Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

前端开发需要注意的一些细节 #98

Open
coconilu opened this issue Oct 22, 2018 · 0 comments
Open

前端开发需要注意的一些细节 #98

coconilu opened this issue Oct 22, 2018 · 0 comments

Comments

@coconilu
Copy link
Owner

coconilu commented Oct 22, 2018

1. 获取元素样式

  1. HTMLElement.style:返回CSSStyleDeclaration实例,表示内联属性
  2. HTMLElement.style.cssText:返回的是内联属性的字符串形式
  3. window.getComputedStyle(element[, pseudoElt]):返回CSSStyleDeclaration实例,表示经过计算得出的最后样式
  4. Element.classList:返回DOMTokenList实例,表示元素class属性,可以通过add、remove等API来添加、删除class样式
  5. Element.className:返回元素class属性的字符串

2. dataset

页面标签的data-*会映射到对应的DOM元素的dataset属性上。

页面标签需要全部小写,可以使用连字符-连接每个单词;
dataset上的属性需要转化为驼峰格式。

比如:

<div id="test" data-my-data="hello"></div>

document.querySelector('#test').dataset.myData === "hello" // true

3. attribute 和 property

attribute翻译成中文术语为“特性”,property翻译成中文术语为“属性”。

attribute

我们在HTML文档里给元素附加的特性:

<div hello="world"></div>

该div元素的attributes就会有hello

attributes是通过setAttribute()removeAttribute()来维护的。

property

property指的是HTML元素对应的DOM对象的键值对属性。

property包含attributes。

4. DOM优化原理和方案

JS 引擎和渲染引擎(浏览器内核)是独立实现的。当我们用 JS 去操作 DOM 时,本质上是 JS 引擎和渲染引擎之间进行了“跨界交流”。这个“跨界交流”的实现并不简单,它依赖了桥接接口作为“桥梁”。

方案:

  1. 用变量缓存DOM
  2. 减少DOM操作——用JS代替DOM操作,借助DocumentFragment

参考

HTMLElement.dataset
attribute和property的区别

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant