[toc]
html元素相关
批量动态插入元素
const loopInsert = (element, attribute, parent) => {
const s = document.createElement(element);
for (let n = 0; n < attribute.length; n++) {
s[attribute[n].key] = attribute[n].value;
}
document.querySelector(parent).appendChild(s);
};
const attribute = [
{ key: 'href', value: `/a/css/b.css` }
{ key: 'rel', value: `stylesheet` }
];
loopInsert('link', attribute, 'head');
滑动到页面指定位置
返回顶部按钮
(function() {
var divEle = document.createElement('div');
var style = 'cursor:pointer;position:fixed;width:60px;height:60px;background:rgba(210,210,210,.5);bottom:30%;right:10%;text-align:center;line-height:60px;color:#fff;border-radius:50%';
divEle.setAttribute('style', style);
divEle.innerHTML = 'Top';
document.body.append(divEle)
divEle.addEventListener('click', function() {
window.scrollTo({
top: 0,
behavior: 'smooth'
});
})
})()
滑动到页面底部
function scrollToPageBottom(){
var s = document.body.scrollHeight || document.documentElement.scrollHeight;
var c = window.innerHeight;
var px = s-c; // 表示滑到底部
if(window.scrollTo) {
window.scrollTo({
top: px,
behavior: "smooth"
});
} else {
document.body.scrollTop = document.documentElement.scrollTop = px;
}
}
任意元素滑动到页面顶部
function backToTop(element) {
var v = element.getBoundingClientRect().top+window.pageYOffset
if(/msie/i.test(navigator.userAgent)) {
window.scrollTo(0,v)
} else {
window.scroll({
top: v,
behavior: 'smooth'
})
}
}
获取本地文件
/* 获取本地文件 */
export const getFileFromLocal = (callback, inputId = 'cusSelectPhoto') => {
let inputElement = document.querySelector(`#${inputId}`)
if (inputElement) {
/* 这里删除的原因是为了防止同一个页面有多个该功能,导致所有的input都挂载同一个回调方法 */
inputElement.parentNode.removeChild(inputElement)
}
inputElement = document.createElement('input')
inputElement.setAttribute('id', inputId)
inputElement.setAttribute('type', 'file')
inputElement.setAttribute('style', 'display:none')
document.body.appendChild(inputElement)
inputElement.addEventListener('change', (e) => {
callback(e.target.files)
})
inputElement.click()
}