他们好,那时他们涂超华 1 两分钟来自学 DOM 有关的此基础操作方式的第二部份,文本尽管单纯,但却是有必要性概括归纳的,期望那些重新整理对他们略有协助。
1、检验原素与否著眼
假定 ele 则表示您要检查和它现阶段与否具备关注点的原素:
const hasFocus = ele === document.activeElement;2、检验 Internet Explorer 应用程序
const isIe = function () {const ua = window.navigator.userAgent; return ua.indexOf(MSIE) > -1 || ua.indexOf(Trident) > -1;};他们也能倚赖 document.documentMode。该特性则表示文件格式的文件格式相容商业模式,在 IE 5-11 中为有理数。其它应用程序回到enum。
const isIE = !!document.documentMode;3、检验 mac OS 应用程序
检查和现阶段应用程序与否在 Mac 上运转:
const isMacBrowser = /Mac|iPod|iPhone|iPad/.test(navigator.platform);4、检验终端应用程序
下列是检查和用户与否从终端应用程序下载的三种方式。
4.1、 检查和userAgent(不所推荐)
// You can add more if you want const isMobile = /Android|BlackBerry|iPad|iPod|iPhone|webOS/i .test(navigator.userAgent);4.2、使用特征检验
检查和应用程序与否支持pointer:coarse媒体查询
const isMobile = function () { const match = window.matchMedia((pointer:coarse)); returnmatch && match.matches;};他们不能倚赖屏幕尺寸,因为终端设备越来越大。
5、检验暗黑商业模式
macOS、Windows 10 等现代操作方式系统允许用户选择他们期望在所有应用程序中设置暗黑和明亮商业模式。
下列屏幕截图取自 macOS 的常规设置的窗格:
能通过查看 prefers-color-scheme 媒体查询来检验该选项。
它能是下列值之一:
light:用户期望在 light 商业模式下查看页面dark:用户期望在暗黑商业模式下查看页面no-preference:系统不知道用户的偏好通过检查和这个媒体查询值,他们能确定用户设置的系统商业模式:
const isDarkMode = window.matchMedia && window.matchMedia((prefers-color-scheme: dark)).matches;6、确定原素的高度和宽度
假定 ele 则表示要计算大小的原素的 DOM。
es const styles = window.getComputedStyle(ele); // 不包含 padding and border constheight = ele.clientHeight –parseFloat(styles.paddingTop) – parseFloat(styles.paddingBottom); const width = ele.clientWidth – parseFloat(styles.paddingLeft) – parseFloat(styles.paddingRight); // 只包含 padding constclientHeight = ele.clientHeight;const clientWidth = ele.clientWidth; // 包含 padding and border constoffsetHeight = ele.offsetHeight;const offsetWidth = ele.offsetWidth; // 包含 padding, border and margin constheightWithMargin = ele.offsetHeight +parseFloat(styles.marginTop) + parseFloat(styles.marginBottom); constwidthWithMargin = ele.offsetWidth +parseFloat(styles.marginLeft) + parseFloat(styles.marginRight);归纳
由于时间原因,那时分享的 DOM 此基础
https://github.com/1milligram/html-dom