經常,我們在浏覽各種網頁的時候,都會有各種動畫效果展示,像下圖所示的是很多網上商城常用的貨品展示方式,同類的貨品並排展現在窗口上,用戶如果看中了哪一款商品想要查看詳情的話,只要將鼠標放上該商品的區域,原本折疊起來的商品便會自動展開,詳情便會展現在用戶面前,而這一動畫,就是利用了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: #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 (http://meyerweb.com/eric/tools/css/reset/) * http://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函數變量復雜,邏輯嚴謹,寫代碼時一定要謹慎小心
以上就是本文的全部內容,希望對大家的學習有所幫助。