如何让direction为left的<marquee>标签滚动至指定位置停止?
实现从右向左滚动并停在指定位置的效果
原生<marquee>标签的控制能力有限,尤其是direction="left"时很难精准控制停止位置,推荐用CSS动画替代,既能实现需求,也更符合现代前端规范。
解决方案代码
<!-- 可视容器:控制显示区域,overflow:hidden 隐藏超出部分 --> <div class="scroll-container"> <!-- 滚动内容容器:nowrap 确保内容不换行 --> <div class="scroll-content"> Welcome to Garden Welcome to Garden Welcome to Garden Welcome to Garden </div> </div> <style> .scroll-container { width: 800px; /* 可视区域宽度,可自定义 */ overflow: hidden; padding: 10px; color: #a4ac86; border-bottom: 1px solid #ccc; /* 替代原有的<hr> */ } .scroll-content { white-space: nowrap; /* 定义滚动动画:从右侧进入,停在指定位置 */ animation: scrollLeftToStop 8s linear forwards; } /* 动画关键帧:起始位置在容器右侧(100%),结束位置设为0(停在容器左侧),可按需调整结束值 */ @keyframes scrollLeftToStop { from { transform: translateX(100%); } to { transform: translateX(0); /* 这里改成你需要的停止位置,比如 translateX(-200px) 或 translateX(-30%) */ } } </style>
关键说明
- 停止位置控制:修改
@keyframes里to的translateX值即可。比如想让内容停在容器左侧偏右20%的位置,就设为translateX(-20%);想停在距离左侧100px的位置,设为translateX(-100px)。 - 滚动速度调整:修改
animation里的8s(动画时长),数值越小速度越快,对应原scrollamount属性。 - 样式兼容:保留了你原有的颜色、内边距样式,用
border-bottom替代<hr>避免布局问题。
备选JavaScript方案(更灵活的动态控制)
如果需要根据交互或动态数据调整停止位置,可使用JS控制:
<div class="scroll-container"> <div class="scroll-content" id="scrollContent"> Welcome to Garden Welcome to Garden Welcome to Garden Welcome to Garden </div> </div> <style> .scroll-container { width: 800px; overflow: hidden; padding: 10px; color: #a4ac86; border-bottom: 1px solid #ccc; } .scroll-content { white-space: nowrap; position: relative; } </style> <script> const content = document.getElementById('scrollContent'); let currentPos = 100; // 起始位置(相对于容器右侧) const targetPos = 0; // 目标停止位置(可自定义) const speed = 2; // 滚动速度,对应原scrollamount const scrollInterval = setInterval(() => { currentPos -= speed; content.style.transform = `translateX(${currentPos}%)`; // 到达目标位置后停止滚动 if (currentPos <= targetPos) { clearInterval(scrollInterval); } }, 20); </script>
内容的提问来源于stack exchange,提问作者Sinn
相关产品推荐
相关产品推荐

