/* dom操作相關js代碼 */
export function addClass(el, className) { // 添加class
if (hasClass(el, className)) {
return
}
let newClass = el.className.split(' ') // 把字符串分割成字符串數組
newClass.push(className)
el.className = newClass.join(' ') // 把數組中的所有元素放入一個字符串
}
export function removeClass(ele, cls) { // 去除class
if (hasClass(ele, cls)) {
let reg = new RegExp("(\\s|^)" + cls + "(\\s|$)")
ele.className = ele.className.replace(reg, " ")
}
}
export function hasClass(el, className) { // 判斷是否有class
let reg = new RegExp('(^|\\s)' + className + '(\\s|$)') // 正則匹配
return reg.test(el.className) // 轉譯一下
}
// 獲取某個月份有多少天
export function getDaysInOneMonth(year, month){
month = parseInt(month, 10)
let d= new Date(year, month, 0)
return d.getDate()
}
// 給小於10的日期和月份加上0
export function Appendzero(obj){
if(obj < 10) return "0" + obj
else return obj
}
// 獲取url後面的參數
export function getQueryString(name) {
let reg = new RegExp("(^ | &)" + name + "=([^&]*)(& | $)","i")
let r = window.location.search.substr(1).match(reg)
if(r!=null) {
return (r[2])
}else{
return null
}
}
// 獲取兄弟節點
export function siblings(obj, opt) {
let a = [] // 用來存兄弟節點
let p = obj.previousSibling
while (p) { // 判斷是否有之前的
if (p.nodeType === 1) {
a.push(p)
}
p = p.previousSibling // 把之前的節點賦值
}
a.reverse() // 反序,這樣元素就是按先後順序的了
let n = obj.nextSibling // 取後面的
while (n) {
if (n.nodeType === 1) {
a.push(n)
}
n = n.nextSibling
}
if (opt) {
let _opt = opt.substr(1)
let b = [] // 用於儲存過濾a數組
if (opt[0] === '.') {
b = a.filter((item) => {
return item.className === _opt
})
} else if (opt[0] === '#') {
b = a.filter((item) => {
return item.id === _opt
})
} else {
b = filter((item) => {
return item.tagName.toLowerCase() === opt
})
}
return b
}
return a
}
// 設置樣式
export function css(obj, json) {
for (let attr in json) {
obj.style[attr] = json[attr]
}
}
// 設置文本內容
export function html(obj) {
if (arguments.length === 1) {
return obj.innerHTML
} else if (arguments.length === 2) {
obj.innerHTML = arguments[1]
}
}
僅爲了下次用的時候copy