const prefix = getVendorPrefix()
function getVendorPrefix() {
var body = document.body || document.documentElement
var style = body.style
var vendor = [‘webkit‘, ‘khtml‘, ‘moz‘, ‘ms‘, ‘o‘]
var i = 0
while (i < vendor.length) {
if (typeof style[vendor[i] + ‘Transition‘] === ‘string‘) {
return vendor[i]
}
i++
}
}
class Node {
constructor(selector) {
if (typeof selector === ‘string‘) {
this.init(document.querySelectorAll(selector))
} else {
if (Object.prototype.toString.apply(selector) === ‘[object NodeList]‘) this.init(selector)
else this.init([selector])
}
}
init(source) {
const names = Object.getOwnPropertyNames(Array.from(source))
names.forEach(item => {
this[item] = source[item]
})
}
find(selector) {
const target = this[0]
return new Node(target.querySelectorAll(selector))
}
parent(selector) {
let target = this[0]
if (!selector && target.parentNode) return new Node(target.parentNode)
while (target.parentNode) {
if (target.parentNode.classList.contains(selector)) return new Node(target.parentNode)
target = target.parentNode
}
return null
}
each(callback) {
for (let i = 0; i < this.length; i++) {
callback && callback(new Node(this[i]), i)
}
return this
}
style(name, style) {
for (let i = 0; i < this.length; i++) {
let item = this[i], attr = name
item.style[attr] = style
attr = `${prefix}${attr[0].toUpperCase()}${attr.slice(1)}`
if (item.style[attr]) item.style[attr] = style
}
return this
}
css(list = {}) {
for (let attr in list) {
this.style(attr, list[attr])
}
return this
}
transform(x, y, time) {
if (x === undefined && y == undefined) {
const target = this[0]
const attr = prefix ? `${prefix}Transform` : `transform`
const transform = target.style[attr]
const reg = /translate([X|Y])?\((.+)?\)/
const rst = reg.exec(transform)
let x = 0;
let y = 0
if (rst) {
if (rst[1] === ‘X‘) x = parseFloat(rst[2])
if (rst[1] === ‘Y‘) y = parseFloat(rst[2])
if (!rst[1]) {
const xy = rst[2].split(‘,‘)
x = parseFloat(xy[0])
y = parseFloat(xy[1])
}
}
return {x, y}
}
if (time !== null) {
this.style(‘transition‘, `all ${time / 1000}s`)
setTimeout(() => {
this.style(‘transition‘, `all 0s`)
}, time)
setTimeout(() => {
this.style(‘transform‘, `translate(${x}px,${y}px)`)
}, 0)
} else {
this.style(‘transform‘, `translate(${x}px,${y}px)`)
}
return this
}
}
function $(selector) {
return new Node(selector)
}
const tops = $(‘.box‘)
.css({
height: ‘1000px‘,
width: ‘1000px‘,
})
.find(‘.top‘).style(‘height‘, ‘150px‘)
.css({
height: ‘1000px‘,
width: ‘1000px‘,
}).parent(‘box‘)
console.log(tops)
原文:https://www.cnblogs.com/jiebba/p/12924894.html