JavaScript 实现长图无缝滚动效果
作者:纸飞机时间:2026-10-24 10:05:44浏览:335
本文介绍了如何使用 JavaScript 结合定时器实现长图的自动滚动效果。通过回顾 setInterval 和 clearInterval 的基本用法,详细展示了构建滚动容器的 CSS 样式及控制图片位置的核心逻辑,包括鼠标悬停停止和移出继续的功能实现。
JavaScript 实现长图无缝滚动效果
本文分享了一段使用 JavaScript 实现长图滚动的完整代码示例,供读者参考学习。
定时器机制回顾
实现长图的自动滚动效果,核心在于对定时器机制的运用。
在深入具体代码之前,我们先回顾一下定时器的基本工作原理。
定时器基础代码示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>定时器回顾</title>
</head>
<body>
<button id="start">开启</button>
<button id="stop">关闭</button>
<script type="text/javascript">
var start = document.getElementById("start");
var stop = document.getElementById("stop");
var num = 0,timer = null;
start.onclick = function (){
// 使用定时器的时候 先清除原有定时器 再开启定时器 可以试着将下边的clearInterval(timer);注释掉然后多次点击开启按钮对比效果
clearInterval(timer);
timer = setInterval(function (){
num++;
console.log(num);
},1000)
}
stop.onclick = function (){
clearInterval(timer);
}
</script>
</body>
</html>
长图滚动核心实现
熟悉定时器后,接下来我们来看实现长图滚动的具体代码实现。
长图滚动完整代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>长图滚动效果</title>
<style>
*{
padding: 0;
margin: 0;
}
body{
background-color: #000;
}
#box{
width: 658px;
height: 400px;
border: 1px solid #ff6700;
margin: 100px auto;
overflow: hidden;
position: relative;
}
#box img{
position: absolute;
top: 0;
left: 0;
}
#box span{
position: absolute;
width: 100%;
height: 50%;
left: 0;
cursor: pointer;
}
#box #top{
top: 0;
}
#box #bottom{
bottom: 0;
}
</style>
</head>
<body>
<div id="box">
<img src="img/timer.jpeg" alt="">
<span id="top"></span>
<span id="bottom"></span>
</div>
<script type="text/javascript">
// 1.获取事件源
var box = document.getElementById('box');
var pic = document.getElementsByTagName('img')[0];
var divTop = document.getElementById('top');
var divBottom = document.getElementById('bottom');
// 2.添加事件
var num = 0,timer = null;
divBottom.onmouseover = function () {
// 清除之前的加速效果
clearInterval(timer);
// 让图片向下滚动
timer = setInterval(function () {
num -= 10;
// 这个-3666是根据图片自己调控的
if(num >= -3666){
pic.style.top = num + 'px';
}else{
clearInterval(timer);
}
},50);
}
divTop.onmouseover = function () {
clearInterval(timer);
// 让图片向上滚动
timer = setInterval(function () {
num += 10;
if(num <= 0){
pic.style.top = num + 'px';
}else{
clearInterval(timer);
}
},100);
}
// 鼠标移开则停止滚动
box.onmouseout = function () {
clearInterval(timer);
}
</script>
</body>
</html>
此处未展示运行效果图,读者可自行复制代码测试,建议准备一张长图以观察效果。
以上内容即为本文的全部分享,希望能为各位的学习提供便利,也欢迎大家继续支持本站。
作者最新文章
JS动态构建复杂嵌套JSON对象的方法
2026-11-05 15:41:52
JS负数取余为什么是负数?详解余数与模运算区别
2026-11-05 13:34:41
JS 解压出现乱码或报错怎么解决?
2026-11-05 12:32:38
JS 中 startsWith、indexOf 与正则判断字符串前缀的对比
2026-11-04 22:19:43
JS解析Excel后怎么将数据转换为JSON格式
2026-11-04 20:58:28
