JavaScript实用方法集合
动态加载js
const loadScript = (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
const hasClass = (el, className) => {
let reg = new RegExp('(^|\\s)' + className + '(\\s|$)')
return reg.test(el.className)
}
为el元素添加某个class
const addClass = (el, className) => {
if (hasClass(el, className)) {
return
}
let newClass = el.className.split(' ')
newClass.push(className)
el.className = newClass.join(' ')
}
为el元素移除某个class
const removeClass = (el, className) => {
if (!hasClass(el, className)) {
return
}
let reg = new RegExp('(^|\\s)' + className + '(\\s|$)', 'g')
el.className = el.className.replace(reg, ' ')
}
获取滚动的坐标
const getScrollPosition = (el = window) => ({
x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft,
y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop
});
页面滚动到顶部
const scrollToTop = () => {
const c = document.documentElement.scrollTop || document.body.scrollTop;
if (c > 0) {
window.requestAnimationFrame(scrollToTop);
window.scrollTo(0, c - c / 8);
}
}
el元素是否在视口范围内
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;
}
去除字符串空格
- 去除所有空格
str.replace(/\s+/g, "")
- 去除前后空格
str.replace(/(^\s*)|(\s*$)/g, "")
- 去除前空格
str.replace(/(^\s*)/g, "")
- 去除后空格
str.replace(/(\s*$)/g, "")
首字母大写
str.replace(/\b\w+\b/g, function (word) {
return word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase();
})
首字母小写
str.replace(/\b\w+\b/g, function (word) {
return word.substring(0, 1).toLowerCase() + word.substring(1).toUpperCase();
})
字母大小写转换
str.split('').map(function (word) {
if (/[a-z]/.test(word)) {
return word.toUpperCase();
} else {
return word.toLowerCase()
}
}).join('')
颜色16进制转RGB、RGBA字符串
export const colorToRGB = (val, opacity) => {
// 16进制颜色值校验规则
var pattern = /^(#?)[a-fA-F0-9]{6}$/;
// 判断是否有设置不透明度
var isOpacity = typeof opacity == 'number';
// 如果值不符合规则返回空字符
if (!pattern.test(val)) {
return '';
}
// 如果有#号先去除#号
var v = val.replace(/#/, '');
var rgbArr = [];
var rgbStr = '';
for (var i = 0; i < 3; i++) {
var item = v.substring(i * 2, i * 2 + 2);
var num = parseInt(item, 16);
rgbArr.push(num);
}
rgbStr = rgbArr.join();
rgbStr = 'rgb' + (isOpacity ? 'a' : '') + '(' + rgbStr + (isOpacity ? ',' + opacity : '') + ')';
return rgbStr;
}
版权声明:
本站所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自
小森森博客!
喜欢就支持一下吧
打赏
微信
支付宝