移动端文字长自动轮播
当你需要在移动端显示长文本时,如何自动对其进行轮播以确保可读性至关重要。以下是一种可行的实现方式:
实现原理
- 利用 CSS 逐字动画:将文本放入一个限制宽度的元素,并在文本上应用逐字轮播动画。如果文本太短而无法滚动,则不会触发动画。
- 使用 JavaScript: 监听文本的宽度变化。如果宽度大于元素的宽度,则启动动画;否则,停止动画。
示例代码
<div class="text-container">
<p>很长的文本,当它超过容器宽度时会自动滚动。</p>
</div>
<style>
.text-container {
width: 200px;
overflow: hidden;
animation: text-scroll 5s infinite;
}
.text-scroll {
animation-fill-mode: forwards;
animation-timing-function: cubic-bezier(0.1, 0.8, 0.2, 1);
}
</style>
<script>
const container = document.querySelector('.text-container');
const text = container.querySelector('p');
function startAnimation() {
if (text.scrollWidth > container.clientWidth) {
container.classList.add('text-scroll');
}
}
function stopAnimation() {
container.classList.remove('text-scroll');
}
text.addEventListener('DOMSubtreeModified', function() {
startAnimation();
});
window.addEventListener('resize', function() {
startAnimation();
});
</script>


















