从零开始JavaScript学习第13天笔记:DOM的应用
一.事件(event)中的this
当一个事件被触发时,事件处理函数(也称为事件监听器)被调用,并且this关键字将指向触发该事件的元素。这使得我们可以在事件处理函数内部访问和操作当前元素。
1.传统function函数
在function函数中,this还是指谁调用了它那么this就是谁。
// 获取元素
const button = document.querySelector("button");
// 添加click事件监听器
button.addEventListener("click", function() {
// 在事件处理函数中,this指向触发事件的元素(button)
console.log("Clicked element:", this);
this.style.backgroundColor = "red";
});
这里的this就是指button
2.箭头函数
箭头函数的this关键字与普通函数的this关键字有所不同。在事件处理函数中使用箭头函数时,this关键字会继承自外部作用域,而不是指向触发事件的元素。
const button = document.querySelector('button');
button.addEventListener('click', () => {
console.log(this); // 输出:Window { ... }
});
二.DOM中对表单的操作
1.获取表单元素
可以使用document.getElementById()或document.querySelector()等方法来获取表单元素
const form = document.getElementById('myForm');
2.获取/设置表单字段的值
可以使用value属性来获取或设置表单字段的值
const input = document.getElementById('myInput');
const inputValue = input.value; // 获取输入框的值
input.value = 'New Value'; // 设置输入框的值为'New Value'
3.提交表单
可以使用submit()方法来提交表单。
let form = document.getElementById('myForm');
form.submit(); // 提交表单
4.阻止表单默认行为
let form = document.getElementById('myForm');
form.addEventListener('submit', (event) => {
event.preventDefault(); // 阻止表单提交
});
5.监听表单字段的变化
const input = document.getElementById('myInput');
input.addEventListener('input', (event) => {
console.log(event.target.value); // 输出输入框的值
});
三.BOM操作
BOM(浏览器对象模型)提供了许多操作浏览器窗口和页面的API。
1.弹窗操作
BOM提供了alert()、confirm()和prompt()方法来创建三种类型的弹窗对话框。alert()用于显示简单的警告消息,confirm()用于显示确认对话框,并返回用户的选择结果,prompt()用于显示提示对话框,用户可以在其中输入信息。
alert('Hello World');
const result = confirm('Are you sure?');
const name = prompt('Please enter your name');
2.窗口和标签页操作
使用window对象可以操作当前窗口或标签页。例如,可以使用open()方法打开新的窗口或标签页,使用close()方法关闭当前窗口或标签页,使用print()方法打印当前页面。
window.open('https://www.baidu.com', '_blank');
window.close();
window.print();
3.导航操作
location对象来操作浏览器的URL。可以使用location.href获取当前页面的URL,使用location.assign()跳转到新的URL,使用location.reload()重新加载当前页面。
let currentURL = location.href;
location.assign('https://www.baidu.com');
location.reload();
4.历史记录操作
使用history对象可以操作浏览器的历史记录。可以使用history.back()返回上一页,使用history.forward()前进到下一页,使用history.go()跳转到指定的历史记录位置。
history.back();
history.forward();
history.go(-2); // 返回两个历史记录位置
5.定时器操作
BOM提供了setTimeout()和setInterval()方法来创建定时器。setTimeout()在一段时间后执行一次回调函数,setInterval()每隔一段时间执行一次回调函数。
setTimeout(() => {
console.log('Hello World');
}, 1000);
setInterval(() => {
console.log('Hello World');
}, 1000);
6.navigator
它提供了有关浏览器和用户代理的信息。navigator对象包含了许多属性,用于获取浏览器的相关信息。
7.window.screen
window.screen是BOM中的一个对象,它提供了有关用户屏幕的信息。
网站常见效果应用
1.工作表单隔行变色效果
1.表单隔行变色
隔行变色
//获取所有的tbody中tr元素
//遍历 隔一行写一种颜色
var arr = document.querySelectorAll("#tb1 tbody tr")
console.log(arr)
for (let i = 0; i < arr.length; i++) {
if (i % 2 == 1) {
arr[i].style.backgroundColor = "blue"
} else if (i % 2 == 0) {
arr[i].style.backgroundColor = "green"
}
}
2.表单点击行变色
<script>
//获取所有的tbody下 tr元素
//给每一个tr设置点击事件
//点了谁 谁的背景颜色就改变 之前点过的要变回去
//排他设计思想: 如果有一种设计同类型的效果有一个是有差异的 希望每次改变差异选项 然后被改过的差异项复位
//先把所有的选项复位 然后排他
var arr2 = document.querySelectorAll("#tb2 tbody tr")
for (let i = 0; i < arr2.length; i++) {
arr2[i].onclick = function () {
//把所有的tr全部改成之前颜色
for (let j = 0; j < arr2.length; j++) {
arr2[j].style.backgroundColor = "white"
}
this.style.backgroundColor = "#999999"
}
}
</script>
3.表单点击列变色
<script>
Object.prototype.indexof = function () {
var arr = this.parentNode.children //调用者的所有兄弟
for (let i = 0; i < arr.length; i++) {
if (arr[i] === this) {
return i
}
}
}
//获取所有的tbody td
//遍历 绑定点击事件
//算出当前点击的元素 是父元素的第x个儿子
//遍历所有的tr 把他们的第x个儿子变色
var arr3 = document.querySelectorAll("#tb3 tbody td")
var arr4 = document.querySelectorAll("#tb3 tbody tr")
for (let i = 0; i < arr3.length; i++) {
arr3[i].onclick = function () {
// console.log(this)
var index = this.indexof()
console.log(index)
//复位
for (let g = 0; g < arr3.length; g++) {
arr3[g].style.backgroundColor = "white"
}
//排他
for (let j = 0; j < arr4.length; j++) {
arr4[j].children[index].style.backgroundColor = "#999999"
}
}
}
</script>
2.拖拽效果
类似于将一个盒子拖着走的效果
<body>
<style>
body {
margin: 0px;
background: #999999;
}
.box {
width: 400px;
height: 300px;
border-radius: 10px;
background-color: white;
position: absolute;
left: 200px;
top: 100px;
cursor: pointer;
}
</style>
<div class="box">
</div>
<script>
let box = document.querySelector(".box")
box.onmousedown = function (e) {
box.style.cursor = "move"
//按下时 记录 盒子的位置 按下时鼠标的位置
let boxX = parseFloat(getComputedStyle(box).left)
let boxY = parseFloat(getComputedStyle(box).top)
let mouseX = e.clientX
let mouseY = e.clientY
document.onmousemove = function (e2) {
console.log(e2)
box.style.left = boxX + e2.clientX - mouseX + "px"
box.style.top = boxY + e2.clientY - mouseY + "px"
}
}
document.onmouseup = () => {
document.onmousemove = null;
box.style.cursor = "pointer"
}
</script>
</body>
3.前端表单验证
在前端开发中,表单验证是一项常见的任务,用于确保用户输入的数据符合预期的格式和要求。
<body>
<form id="myForm" onsubmit="validateForm(event)">
邮箱:<input type="email" id="email" required><br/>
密码:<input type="password" id="name" required><br/>
<input type="submit" value="Submit">
</form>
<script>
function validateForm(event) {
event.preventDefault(); // 阻止表单提交
// 获取表单字段的值
const name = document.getElementById('name').value;
const email = document.getElementById('email').value;
// 检查字段是否为空
if (name.trim() === '' || email.trim() === '') {
alert('请填写所有字段');
return;
}
// 检查邮箱格式是否正确
const emailRegex = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (!emailRegex.test(email)) {
alert('请输入有效的邮箱地址');
return;
}
// 执行其他操作,如提交表单数据给后端
console.log('表单验证通过');
// ...
}
</script>
</body>
4.图片放大器
body>
<style>
.goodsbox {
width: 300px;
height: 168.75px;
background-color: saddlebrown;
position: absolute;
left: 100px;
top: 100px;
background-image: url("./img/1.jpg");
background-size: 300px 168.75px;
cursor: move;
}
.mask {
width: 40px;
height: 40px;
background-color: rgba(251, 195, 31, 0.5);
position: absolute;
left: 100px;
top: 20px;
display: none;
}
.goodsbox:hover .mask {
display: block;
}
.big {
position: absolute;
left: 420px;
top: 100px;
width: 370px;
height: 370px;
overflow: hidden;
display: none;
}
.img1 {
width: 2775px;
height: 1560.9375px;
position: absolute;
/* left: -10px; */
}
</style>
<div class="goodsbox">
<div class="mask"></div>
</div>
<div class="big">
<img class="img1" src="./img/1.jpg" alt="">
</div>
<script>
let goodsbox = document.querySelector(".goodsbox")
let mask = document.querySelector(".mask")
let img1 = document.querySelector(".img1")
let big = document.querySelector(".big")
goodsbox.onmouseenter = function () {
big.style.display = "block"
}
goodsbox.onmouseleave = function () {
big.style.display = "none"
}
goodsbox.onmousemove = function (e) {
console.log(e.clientX)
let x = e.clientX - goodsbox.offsetLeft - mask.offsetWidth / 2
let y = e.clientY - goodsbox.offsetTop - mask.offsetHeight / 2
if (x <= 0) {
x = 0
}
if (x >= (300 - 40)) {
x = 300 - 40
}
if (y <= 0) {
y = 0
}
if (y >= 168.75 - 40) {
y = 168.75 - 40
}
mask.style.left = x + "px"
mask.style.top = y + "px"
img1.style.left = -x * 370 / 40 + "px"
img1.style.top = -y * 370 / 40 + "px"
}
// 300*(370/40)
</script>
</body>