sky-message 编写消息提示插件

首先介绍一下我的npm插件:

sky-messageicon-default.png?t=N7T8https://www.npmjs.com/package/sky-message

实现

我使用tailwindcssdaisyui做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') //调用方法

  • 15
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Chelase

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值