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", onm ouseMove); window.addEventListener("mouseup", onm ouseUp); }; // 监听mousemove事件 function onm ouseMove(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 onm ouseUp(e) { // 标记拖拽结束 isDragging = false; // 移除mousemove和mouseup事件的监听器 window.removeEventListener("mousemove", onm ouseMove); window.removeEventListener("mouseup", onm ouseUp); } </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>
标签:function,选项卡,05,08,js,window,var,document,display From: https://www.cnblogs.com/iuniko/p/18181100