JS常用方法
监听元素进入隐藏
type CONFIG_IF = {
dom: Element;
showOnce?: boolean;
onShow?: () => void;
onHidden?: () => void;
}[];
function elementsVisibleChange(configs: CONFIG_IF) {
const intersectionObserverA = new IntersectionObserver(entries => {
for (let index = 0; index < entries.length; index++) {
const {
intersectionRatio, target } = entries[index];
const {
onShow, onHidden, showOnce = false } = configs[index];
if (intersectionRatio > 0) {
onShow && onShow();
showOnce && intersectionObserverA.unobserve(target);
} else {
onHidden && onHidden();
}
}
});
for (let index = 0; index < configs.length; index++) {
intersectionObserverA.observe(configs[index]?.dom);
}
}
```js
// 计算文字宽度
function getTextWidth(text, font = '400 14px arial') {
// re-use canvas object for better performance
var canvas = getTextWidth.canvas || (getTextWidth.canvas = document.createElement("canvas"));
var context = canvas.getContext("2d");
context.font = font;
var metrics = context.measureText(text);
return metrics.width;
}
// 判断当前元素是否在可视区域
const isInView = (el) => {
var rect = el.getBoundingClientRect()
var elemTop = rect.top
var elemBottom = rect.bottom
// 元素全部出现在视窗
var isVisible = (elemTop >= 0) && (elemBottom <= window.innerHeight);
return isVisible;
}
// 获取url参数(解决中文乱码问题)
function getUrlQuery(url = '') {
url = url || location.search; // 获取url中"?"符后的字串
const theRequest = {
};
if (url.indexOf('?') !== -1) {
const str = url