检测元素上是否css选择器
// Return true if `el` matches the CSS selector `selector`
const matches = function(el,selector) {
return (
el.matches ||
el.matchesSelector ||
el.msMatchesSelector ||
el.mozMatchesSelector ||
el.webkitMatchesSelector ||
el.oMatchesSelector
).call(el, selector);
}
检测元素是否有某个类
el.classList.contains('className');
检测一个元素是否是一个元素的后代
const isDescendant = parent.contains(child);
检测元素是否在视口中
const isViewport = function(el) {
const rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
rect.right <= (window.innerWidth || document.documentElement.clientWidth)
);
}
检测代码是否在浏览器中运行
const isBrowser = typeof window === 'object' && typeof document === 'object';
检测浏览器是否支持原生日期输入框
const isDateInputSupported = function () {
// 创建一个输入框
const el = document.createElement('input');
// 设置输入框的属性
el.setAttribute('type', 'date');
const invalidValue = 'not-a-valid-date';
// 设置默认值
el.setAttribute('value', invalidValue);
// 如果浏览器支持日期输入框,
// 它不会影响 `value` 属性
// `el.value` 将是一个空字符串
// 在另一种情况下,输入被视为普通文本输入
// 并且 `el.value` 返回默认值
return el.value !== invalidValue;
};
检测浏览器是否支持触摸事件
const touchSupported = 'ontouchstart' in window || (window.DocumentTouch && document instanceof DocumentTouch);
每天一个javascript操作dom方法,学到了,点个赞吧