// html便捷操作js
/**
* 去除字符串中的html标签
* @param {*} str
* @returns
*/
export const removehtmltag = (str) => {
return str.replace(/<[^>]+>/g, '')
}
/**
* 动态引入js
* @param {*} src
*/
export const injectScript = (src) => {
const s = document.createElement('script');
s.type = 'text/JavaScript';
s.async = true;
s.src = src;
const t = document.getElementsByTagName('script')[0];
t.parentNode.insertBefore(s, t);
}
/**
* el是否包含某个class
* @param {*} el
* @param {*} className
* @returns
*/
export const hasClass = (el, className) => {
let reg = new RegExp('(^|\\s)' + className + '(\\s|$)')
return reg.test(el.className)
}
/**
* el添加某个class
* @param {*} el
* @param {*} className
* @returns
*/
export const addClass = (el, className) => {
if (hasClass(el, className)) {
return
}
let newClass = el.className.split(' ')
newClass.push(className)
el.className = newClass.join(' ')
}
/**
* el去除某个class
* @param {*} el
* @param {*} className
* @returns
*/
export const removeClass = (el, className) => {
if (!hasClass(el, className)) {
return
}
let reg = new RegExp('(^|\\s)' + className + '(\\s|$)', 'g')
el.className = el.className.replace(reg, ' ')
}
/**
* 获取滚动的坐标
* @param {*} el
* @returns
*/
export const getScrollPosition = (el = window) => ({
x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft,
y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop
});
/**
* 滚动到顶部
*/
export const scrollToTop = () => {
const c = document.documentElement.scrollTop || document.body.scrollTop;
if (c > 0) {
window.requestAnimationFrame(scrollToTop);
window.scrollTo(0, c - c / 8);
}
}
/**
* el是否在视口范围内
* @param {*} el
* @param {*} partiallyVisible
* @returns
*/
export const elementIsVisibleInViewport = (el, partiallyVisible = false) => {
const { top, left, bottom, right } = el.getBoundingClientRect();
const { innerHeight, innerWidth } = window;
return partiallyVisible
? ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) &&
((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth))
: top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth;
}
/**
* 根据URL地址下载文件
* @param {*} url
* @returns
*/
export const download = (url) => {
var isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
var isSafari = navigator.userAgent.toLowerCase().indexOf('safari') > -1;
if (isChrome || isSafari) {
var link = document.createElement('a');
link.href = url;
if (link.download !== undefined) {
var fileName = url.substring(url.lastIndexOf('/') + 1, url.length);
link.download = fileName;
}
if (document.createEvent) {
var e = document.createEvent('MouseEvents');
e.initEvent('click', true, true);
link.dispatchEvent(e);
return true;
}
}
if (url.indexOf('?') === -1) {
url += '?download';
}
window.open(url, '_self');
return true;
}
08-31