1. 程式人生 > 程式設計 >JavaScript實現長圖滾動效果

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/
java
script"> 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 (){www.cppcns.com
num++; console.程式設計客棧log(num); },1000) } stop.onclick = function (){ clearInterval(timer); } </script> </body> </html>

溫習完定時器內容後,來看長圖滾動的程式碼:

<!DOCTYPE html>
<html lang="en">
<head&www.cppcns.com
gt; <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="JavaScript實現長圖滾動效果"> <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'www.cppcns.com); 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>

這裡不放效果圖了,需要可以自己試試(記得找長圖)

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。