简单描述一下如何用js+html+css如何实现文字滚动的效果
style样式:
<style>
.button{
width: 200px;
height: 60px;
line-height: 60px;
text-align: center;
border-radius: 40px;
border:transparent;
font-size: 20px;
overflow: hidden;
position: relative;
}
.button .divs{
/* animation: scroll 2s linear infinite; */
position: absolute;
width: 100%;
height: 100%;
left: 0px;
top: 0px;
}
.button .divs div{
height: 60px;
}
// html结构:
<button class="button">
<div class="divs">
<div>滚动1</div>
<div>滚动2</div>
<div>滚动1</div>
</div>
</button>
// js代码
<script>
window.addEventListener("DOMContentLoaded",function(){
let divs = document.querySelector(".button .divs");
// 获取每个文本的高度
let height = divs.querySelector("div").offsetHeight;
let currentPosition = 0
function move(){
currentPosition -= 1; // 每次向上移动 1px
divs.style.top = currentPosition + 'px';
// 当滚动到倒数第二个文本时,重置位置
if (Math.abs(currentPosition) >= height * 2) {
currentPosition = 0; // 重置位置
}
requestAnimationFrame(move)
}
requestAnimationFrame(move)
})
</script>
css3写法:
<style>
.button{
width: 200px;
height: 60px;
line-height: 60px;
text-align: center;
border-radius: 40px;
border:transparent;
font-size: 20px;
overflow: hidden;
position: relative;
}
.button .divs{
animation: scroll 2s linear infinite;
/* position: absolute;
width: 100%;
height: 100%;
left: 0px;
top: 0px; */
}
.button .divs div{
height: 60px;
/* left: 0px; */
/* top: 0px; */
}
@keyframes scroll {
0%{
transform: translateY(0);
}
/* 50%{
transform: translateY(-120px);
} */
100%{
transform: translateY(-120px);
}
}
</style>
html如上面所示,这样就可以实现按钮文字滚动特效了。