JavaScript 動畫效果
JavaScript 動畫效果
一:簡介
通過JavaScript動態改變元素位置來實現動畫效果。執行個體、滑鼠移動到連結、在下方顯示對應圖片。主要是網頁的分層結構思想的應用。
二:重點
CSS中元素的position屬性、overflow屬性 varvariable = setTimeout("function", interval);//定時觸發函數 clearTimeout(variable);//清除定時觸發函數、variable是setTimeout的傳回值。 parseInt(str);//將字串轉換成整數 parseFloat(str);//將字串轉換成浮點數 Math.ceil(number);//向上取整 Math.floor(number);//向下取整 Math.round(number);//四捨五入
三:實現
效果:
list.html:
Web Design <script src="../js/moveElementImprove.js"></script> <script src="../js/list.js"></script> <script src="../js/addLoadEvent.js"></script>Web DesignThese are the things you should know.
- Structure
- Presentation
- Behavior
list.css:
#slideShow { width: 100px; height: 100px; position: relative; overflow: hidden;}#preview { position: absolute;}
list.js:
/** * Created by andychen on 2015/1/9. */function prepareSlideShow() { var div = document.createElement("div"); div.id = "slideShow"; var img = document.createElement("IMG"); img.id = "preview"; img.src = "../images/preview.png"; img.alt = "building blocks of web design"; div.appendChild(img); insertAfter(document.getElementById("linkList"), div); var links = document.getElementsByTagName("a"); links[0].onmouseover = function () { moveElementImprove("preview", -100, 0, 10); }; links[1].onmouseover = function () { moveElementImprove("preview", -200, 0, 10); }; links[2].onmouseover = function () { moveElementImprove("preview", -300, 0, 10); }}function insertAfter(targetTag, newTag) { var parent = targetTag.parentNode; if (parent.lastChild == targetTag) { parent.appendChild(newTag); } else { parent.insertBefore(newTag, targetTag.nextSibling); }}
moveElementImprove.js:
/** * Created by andychen on 2015/1/9. */function moveElementImprove (elementId, final_x, final_y, interval) { var elem = document.getElementById(elementId); if(elem.movement) { clearTimeout(elem.movement); } if(!elem.style.left) { elem.style.left = '0px'; } if(!elem.style.top) { elem.style.top = '0px'; } var topPosition = parseInt(elem.style.top); var leftPosition = parseInt(elem.style.left); var dist = 0; if (topPosition < final_y) { dist = Math.ceil((final_y - topPosition) / 10); topPosition += dist; } if (topPosition > final_y) { dist = Math.ceil((topPosition - final_y) / 10); topPosition -= dist; } if (leftPosition < final_x) { dist = Math.ceil((final_x - leftPosition) / 10); leftPosition += dist; } if (leftPosition > final_x) { dist = Math.ceil((leftPosition - final_x) / 10); leftPosition -= dist; } if (topPosition == final_y && leftPosition == final_x) { return true; } elem.style.top = topPosition + 'px'; elem.style.left = leftPosition + 'px'; var repeat = "moveElementImprove('"+elementId+"', "+final_x+", "+final_y+", "+interval+")"; elem.movement = setTimeout(repeat, interval);}
addLoadEvent.js 前文已經提到。