1.向下滑動
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>向下滑動</title> <style> body { margin: 0px; } #show { width: 200px; /* 高度為 0 */ height: 100px; background-color: lightcoral; margin: 0 auto; /* 設置為隱藏 */ /*display: none;*/ } </style></head><body><div id="show"></div><script> var show = document.getElementById('show'); /*show.style.display = 'block'; var t = setInterval(function(){ var style = window.getComputedStyle(show,null); var height = parseInt(style.height); // 判斷當前的高度是否為 400 if (height >= 400){ clearInterval(t); } else { height++; show.style.height = height + 'px'; } },50);*/ slideDown(show,400); /* 將上述實現的向下滑動效果,封裝在一個固定的函數中 * 設計當前實現向下滑動效果函數的形參 * elem - 表示實現向下滑動效果的元素 * maxHeight - 表示元素向下滑動的最大高度值 * 函數的邏輯與默認設置CSS樣式屬性的值無關 */ function slideDown(elem, maxHeight){ // 操作的元素默認的display值為none elem.style.display = 'block'; elem.style.height = '0px'; var t = setInterval(function(){ var style = window.getComputedStyle(elem,null); var height = parseInt(style.height); // 判斷當前的高度是否為 400 if (height >= maxHeight){ clearInterval(t); } else { height++; elem.style.height = height + 'px'; } },50); }</script></body></html>2.移動效果
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>移動效果</title> <style> body { margin: 0px; } #box { width: 100px; height: 100px; background-color: lightcoral; position: absolute; left: 100px; top: 100px; } </style></head><body><div id="box"></div><script> var box = document.getElementById('box'); box.onclick = function(){ clearInterval(t); } /* * 向右移動 * 當前元素移動到頁面的最右邊時 -> 向左移動 * 向左移動 * 當前元素移動到頁面的最左邊時 -> 向右移動 */ var flag = false;// 默認表示向右 var speed = 1;// 表示每次變化的值 t = setInterval(function(){ //speed += 0.01; // 獲取當前頁面的寬度 var WIDTH = window.innerWidth; var style = window.getComputedStyle(box,null); var left = parseInt(style.left); var width = parseInt(style.width); // 判斷當前元素移動的方向 if (flag){// 向左移動 left -= speed; } else {// 向右移動 left += speed; } // 判斷什么情況下,向左移動;判斷什么情況下,向右移動 if ((left + width) >= WIDTH){// 向左移動 flag = true; } else if (left <= 0){// 向右移動 flag = false; } box.style.left = left + 'px'; },10);</script></body></html>
新聞熱點
疑難解答
圖片精選