首先介绍一下我的npm插件:
sky-messagehttps://www.npmjs.com/package/sky-message
实现
我使用tailwindcss和daisyui做css基础 当然也可以选择自己编写样式
创建元素
let topOffset = 0;
const create = (msg, className, d) => {
// 创建元素
const Alert = document.createElement('div')
Alert.className = className
Alert.style.position = 'fixed' // 添加定位
Alert.style.top = `${topOffset}px` // 添加top位置
Alert.role = 'alert'
topOffset += 65 // 每次生成元素后 top都会增加65
// 创建svg
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg')
svg.setAttribute('class', 'stroke-current shrink-0 h-6 w-6')
svg.setAttribute('fill', 'none')
svg.setAttribute('viewBox', '0 0 24 24')
const path = document.createElementNS('http://www.w3.org/2000/svg', 'path')
path.setAttribute('stroke-linecap', 'round')
path.setAttribute('stroke-linejoin', 'round')
path.setAttribute('stroke-width', '2')
path.setAttribute('d', d)
svg.appendChild(path)
const span = document.createElement('span')
span.textContent = msg
// 将元素添加到对应的位置
Alert.appendChild(svg)
Alert.appendChild(span)
body.appendChild(Alert)
setTimeout(() => {
Alert.remove()
topOffset -= 65 // 移除元素时减去相应的上边距
updateNextElementPosition()
}, 3000)
}
const updateNextElementPosition = () => {
// 获取所有class为alert的元素
const elements = document.querySelectorAll('.alert')
// 循环所有alert并将他们的位置减去65 达到一个向上的效果
for (let i = 0; i < elements.length; i++) {
elements[i].style.top = `${parseInt(elements[i].style.top) - 65}px`
}
}
导出并调用
export default {
success (msg) {
create(
msg,
'alert alert-success z-50 animation-top',
'M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z'
)
}
}
import Message from './index.js' // 替换为你的路径
Message.success('I\'m success info') //调用方法