上周,一位同学好奇地向我咨询如何开发移动端的通知消息功能。尽管市面上存在众多UI组件可以直接使用,但我仍选择从零开始,手动实现这一功能。
话不多说直接上效果
实现步骤
HTML
<div class="container">
<div class="tip">
<i class="iconfont icon-xiaolaba icon-lb"></i>
<div class="text-wrapper">
<div class="text" data-time="0" data-left="0">
您有一封新的电子邮件,发件人:[mailto:example@example.com],主题:关于我们的会议。
</div>
</div>
</div>
`
CSS
<link rel="stylesheet" href="https://at.alicdn.com/t/c/font_4100171_y3g4zojl15.css">
<style>
.container {
width: 375px;
height: 660px;
margin: 50px auto;
border-radius: 12px;
border: 2px solid #ededed;
position: relative;
white-space: nowrap;
overflow: hidden;
}
.tip {
position: relative;
height: 40px;
line-height: 40px;
padding-left: 16px;
display: flex;
color: #ed6a0c;
font-size: 16px;
white-space: nowrap;
background-color: #fffbe8;
}
.icon-lb {
padding-right: 5px;
}
.text-wrapper {
flex: 1;
position: relative;
overflow: hidden;
}
.text {
position: absolute;
white-space: nowrap;
animation: move var(--time) linear infinite;
}
@keyframes move {
0% {
transform: translateX(0);
}
100% {
transform: translateX(var(--left));
}
}
</style>
JS
<script>
const dom = document.querySelector(".text");
const textWrap = document.querySelector('.text-wrapper')
const speed = 50;//速度
function init () {
const {width} = dom.getBoundingClientRect();//文本宽度
const wrapperWidth = textWrap.getBoundingClientRect()//容器宽度
const time = (width / speed).toFixed(2);
//如果文本宽度短不需要移动动画
if (width > wrapperWidth.width) {
// 设置CSS变量的值
dom.style.setProperty("--time", time + "s");
dom.style.setProperty("--left", -width + "px"); // 注意添加'px'单位
}
}
init();
</script>
下期预告
实现多个提示消息上下自动切换的效果