1.表單驗證
function validateForm() { var name = document.forms["myForm"]["name"].value; if (name == "") { alert("Name must be filled out"); return false; } // 更多的驗證... return true; }
2.DOM 操作
var element = document.getElementById("myElement"); element.textContent = "Hello, World!"; element.style.color = "blue";
3.事件監聽
var button = document.getElementById("myButton"); button.addEventListener("click", function() { alert("Button clicked!"); });
4.建立元素
var newDiv = document.createElement("div"); newDiv.textContent = "New div created!"; document.body.appendChild(newDiv);
5.定時器
var count = 0; var timer = setInterval(function() { console.log(count); count++; if (count >= 10) { clearInterval(timer); } }, 1000);
6.獲取 URL 引數'
function getURLParameter(name) { var url = window.location.href; name = name.replace(/[\[\]]/g, '\\$&'); var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'); var results = regex.exec(url); if (!results) return null; if (!results[2]) return ''; return decodeURIComponent(results[2].replace(/\+/g, ' ')); }
7.AJAX 請求
var xhr = new XMLHttpRequest(); xhr.open("GET", "https://api.example.com/data", true); xhr.onreadystatechange = function () { if (xhr.readyState == 4 && xhr.status == 200) { console.log(xhr.responseText); } }; xhr.send();
8.Cookie 操作
function setCookie(name, value, days) { var expires = ""; if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); expires = "; expires=" + date.toUTCString(); } document.cookie = name + "=" + (value || "") + expires + "; path=/"; } function getCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for (var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) == ' ') c = c.substring(1, c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length); } return null; }
9.拖拽元素
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>拖拽元素</title> <style> body { margin: 0; } #draggable { width: 100px; height: 100px; background-color: #1890ff; position: relative; cursor: pointer; } </style> </head> <body> <div id="draggable"></div> </body> </html> <script> // 獲取需要拖拽的元素 var draggableElement = document.getElementById("draggable"); // 拖拽相關的變數 var isDragging = false; var currentX, currentY, initialX, initialY, offsetX, offsetY; // 監聽mousedown事件 draggableElement.onmousedown = function (e) { // 防止預設行為(例如,文字選擇) e.preventDefault(); // 標記為拖拽中 isDragging = true; // 計算滑鼠指標相對於元素的初始位置 offsetX = e.clientX - draggableElement.getBoundingClientRect().left; offsetY = e.clientY - draggableElement.getBoundingClientRect().top; // 獲取元素當前的偏移量 initialX = parseInt( window.getComputedStyle(draggableElement).getPropertyValue("left") || "0", 10 ); initialY = parseInt( window.getComputedStyle(draggableElement).getPropertyValue("top") || "0", 10 ); // 新增mousemove和mouseup事件的監聽器到window物件上,這樣即使滑鼠移動到了元素外部也能繼續拖拽 window.addEventListener("mousemove", onMouseMove); window.addEventListener("mouseup", onMouseUp); }; // 監聽mousemove事件 function onMouseMove(e) { if (!isDragging) return; // 計算新的位置 currentX = e.clientX - offsetX; currentY = e.clientY - offsetY; // 限制拖拽的範圍(可選) // 例如,限制在視口內 currentX = Math.max( 0, Math.min(currentX, window.innerWidth - draggableElement.offsetWidth) ); currentY = Math.max( 0, Math.min(currentY, window.innerHeight - draggableElement.offsetHeight) ); // 更新元素的位置 draggableElement.style.left = currentX + "px"; draggableElement.style.top = currentY + "px"; } // 監聽mouseup事件 function onMouseUp(e) { // 標記拖拽結束 isDragging = false; // 移除mousemove和mouseup事件的監聽器 window.removeEventListener("mousemove", onMouseMove); window.removeEventListener("mouseup", onMouseUp); } </script>
10.捲軸監聽
// 監聽滾動事件 window.addEventListener('scroll', function(event) { // 獲取捲軸的垂直位置 var scrollTop = window.pageYOffset || document.documentElement.scrollTop; // 獲取捲軸的水平位置(在需要的情況下) var scrollLeft = window.pageXOffset || document.documentElement.scrollLeft; // 輸出捲軸的位置 console.log('x軸:' + scrollTop);
console.log('y軸:' + scrollLeft);
});
11.1 選項卡(純css版):label觸發點選控制type=radio的input顯示與隱藏
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> /* 隱藏所有選項卡內容 */ .tab-content .tab { display: none; } /* 選中radio時顯示對應的選項卡內容 */ #tab1:checked ~ .tab-content #content1, #tab2:checked ~ .tab-content #content2, #tab3:checked ~ .tab-content #content3 { display: block; } /* 樣式化選項卡按鈕 */ .tabs input[type="radio"] { display: none; /* 隱藏radio input */ } .tabs label { display: inline-block; margin-right: 10px; padding: 5px 10px; border: 1px solid #ccc; cursor: pointer; } /* 選中狀態的選項卡按鈕樣式 */ .tabs input[type="radio"]:checked + label { background-color: #eee; border-bottom: 1px solid #fff; /* 防止底部出現雙重邊框 */ } /* 其他可選樣式 */ .tab-content { margin-top: 20px; /* 選項卡內容與選項卡按鈕之間的間距 */ } /* 根據需要新增更多樣式 */ </style> </head> <body> <div class="tabs"> <input type="radio" id="tab1" name="tabs" checked /> <label for="tab1">選項卡1</label> <input type="radio" id="tab2" name="tabs" /> <label for="tab2">選項卡2</label> <input type="radio" id="tab3" name="tabs" /> <label for="tab3">選項卡3</label> <div class="tab-content"> <div class="tab" id="content1"> <p>這是選項卡1的內容。</p> </div> <div class="tab" id="content2"> <p>這是選項卡2的內容。</p> </div> <div class="tab" id="content3"> <p>這是選項卡3的內容。</p> </div> </div> </div> </body> </html>
11.2.選項卡(js版)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> .tab-link { cursor: pointer; } .tab-content { display: none; } .tab-content.active { display: block; } </style> </head> <body> <div class="tabs"> <button class="tab-link" data-tab="tab1">選項卡1</button> <button class="tab-link" data-tab="tab2">選項卡2</button> <button class="tab-link" data-tab="tab3">選項卡3</button> <div class="tab-content" id="tab1">這是選項卡1的內容</div> <div class="tab-content" id="tab2">這是選項卡2的內容</div> <div class="tab-content" id="tab3">這是選項卡3的內容</div> </div> </body> </html> <script> // 獲取所有的選項卡連結和內容 const tabLinks = document.querySelectorAll(".tab-link"); const tabContents = document.querySelectorAll(".tab-content"); // 為每個選項卡連結新增點選事件監聽器 tabLinks.forEach(function (tabLink) { tabLink.addEventListener("click", function () { // 移除所有內容塊的啟用狀態 tabContents.forEach(function (tabContent) { tabContent.classList.remove("active"); }); // 啟用對應的選項卡內容 const tabToShow = document.getElementById(tabLink.dataset.tab); if (tabToShow) { tabToShow.classList.add("active"); } }); }); // 如果有的話,啟用第一個選項卡的內容 if (tabContents[0]) { tabContents[0].classList.add("active"); } </script>
12.輪播圖
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> .carousel { position: relative; width: 500px; height: 500px; margin: 50px auto 0; border: 1px solid #f2f2f2; } .carousel-images { display: flex; transition: transform 0.5s ease; } .carousel-images img { width: 500px; } /* 隱藏除第一張外的所有圖片 */ .carousel-images img:not(:first-child) { display: none; } .prev, .next { width: 50px; height: 50px; position: absolute; top: 50%; background-color: rgba(0, 0, 0, 0.5); color: #fff; border-radius: 50%; text-align: center; font-size: 32px; line-height: 50px; cursor: pointer; } .prev { left: 10px; } .next { right: 10px; } </style> </head> <body> <div class="carousel"> <div class="carousel-images"> <img src="https://www.foodiesfeed.com/wp-content/uploads/2023/08/grilled-crispy-pork-with-rice.jpg" alt="Image 1" /> <img src="https://www.foodiesfeed.com/wp-content/uploads/2023/12/seafood-soup.jpg" alt="Image 2" /> <img src="https://www.foodiesfeed.com/wp-content/uploads/2023/04/delicious-steak-with-herbs-cut-on-slices.jpg" alt="Image 3" /> <!-- 更多圖片... --> </div> <div class="prev"><</div> <div class="next">></div> </div> </body> </html> <script> // 獲取需要的DOM元素 const carouselImages = document.querySelector(".carousel-images"); const images = carouselImages.querySelectorAll("img"); const prevButton = document.querySelector(".prev"); const nextButton = document.querySelector(".next"); let currentImageIndex = 0; // 設定下一張圖片的顯示 function showNextImage() { // 隱藏當前圖片 images[currentImageIndex].style.display = "none"; // 更新索引並顯示下一張圖片(或第一張,如果當前是最後一張) currentImageIndex = (currentImageIndex + 1) % images.length; images[currentImageIndex].style.display = "block"; console.log("設定下一張圖片的顯示", currentImageIndex); } // 設定上一張圖片的顯示 function showPrevImage() { // 隱藏當前圖片 images[currentImageIndex].style.display = "none"; // 更新索引並顯示上一張圖片(或最後一張,如果當前是第一張) currentImageIndex = (currentImageIndex - 1 + images.length) % images.length; images[currentImageIndex].style.display = "block"; console.log("設定上一張圖片的顯示", currentImageIndex); } // 繫結點選事件 prevButton.addEventListener("click", showPrevImage); nextButton.addEventListener("click", showNextImage); // 自動播放(可選) // setInterval(showNextImage, 3000); // 每3秒切換到下一張圖片 </script>