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='https://www.haobala.com/bcjs/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>
这里不放效果图了,需要可以自己试试(记得找长图)
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持好吧啦网。
相关文章:
