我們在瀏覽各類網頁時,常常會遇到琳瑯滿目的動畫效果。像下圖這樣的貨品展示方式,便是許多網上商城常用的手法:同類商品並排陳列,用戶看中哪一款、想把鼠標移上去看詳情時,原本折疊的商品便會自動展開,把細節呈現在眼前。而這段動畫,正是借助 DOM 與 JS 結合來實現的。今天的小練習,就是要還原這個效果。

首先,用 HTML 搭出頁面的基本框架,把四張圖封裝進一個名為「container」的 div 塊裡:
<!doctype html> <meta charset="UTF-8"> <html> <head> <title> 鼠標滑過頁面自動變大 </title> <link rel="stylesheet" href="styles/reset.css" /> <link rel="stylesheet" href="styles/slidingdoors.css" /> <script src="slidlingdoors.js"></script> </head> <body> <div id="container"> <img src="./images/door1.png"/> <img src="./images/door2.png"/> <img src="./images/door3.png"/> <img src="./images/door4.png"/> </div> </body> </html>
接著,我用兩個樣式表修飾大體的外觀,分別是 slidingdoors.css 與 reset.css:
slidingdoors.css和reset.css: #container { height: 477px; margin: 0 auto; border-right: 1px solid #ccc; border-bottom: 1px solid #ccc; overflow: hidden; position: relative; } #container img { position: absolute; display: block; left: 0; border-left: 1px solid #ccc; }
/** * Eric Meyer's Reset CSS v2.0 (https://meyerweb.com/eric/tools/css/reset/) * https://cssreset.com */ html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video { margin: 0; padding: 0; border: 0; font-size: 100%; font: inherit; vertical-align: baseline; } /* HTML5 display-role reset for older browsers */ article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section { display: block; } body { line-height: 1; } ol, ul { list-style: none; } blockquote, q { quotes: none; } blockquote:before, blockquote:after, q:before, q:after { content: ''; content: none; } table { border-collapse: collapse; border-spacing: 0; }
接下來就是核心的滑動效果了,JS 代碼如下:
window.onload=function(){ var box=document.getElementById("container"); var imgs=box.getElementsByTagName("img"); var imgwidth=imgs[0].offsetWidth; var exposewidth=160; var boxwidth=imgwidth+exposewidth*(imgs.length-1); box.style.width=boxwidth+'px'; function setImgPos(){ for(var i=1;i<imgs.length;i++) { imgs[i].style.left=imgwidth+exposewidth*(i-1)+'px'; } } setImgPos(); var translate=imgwidth-exposewidth; for(var i=0;i<imgs.length;i++) { (function(i){ imgs[i].onmouseover=function(){ setImgPos(); for(var j=1;j<=i;j++) { imgs[j].style.left=parseInt(imgs[j].style.left,10)-translate+'px'; } }; })(i); } };
調好之後的效果圖如下:

遇到的問題:
1. 圖片復位函數裡,i、j 兩個變量一不小心就搞混了;
2. 做出來的效果中,一張圖片復位後,把其餘尚未復位的圖片全擋住了——根源還是在復位函數出了小差錯。
經驗:JS 函數的變量繁多、邏輯嚴謹,寫代碼時一定要多留個心眼,謹慎小心。
以上就是本文的全部內容,希望對你的學習有所幫助。