js长图滚动效果 JavaScript实现长图滚动效果

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

js长图滚动效果 JavaScript实现长图滚动效果

知识进脑的肖老千啊   2021-04-29 我要评论
想了解JavaScript实现长图滚动效果的相关内容吗,知识进脑的肖老千啊在本文为您仔细讲解js长图滚动效果的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:js,长图滚动,下面大家一起来学习吧。

长图的滚动会涉及定时器:

我们先来回顾下定时器:

<!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>

这里不放效果图了,需要可以自己试试(记得找长图)

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们