1,什么是DOM?
- DOM(Document Object Model——文档对象模型)
- 作用:操作网页文档,实现部分特效和用户交互
- 核心思想:把网页内容当作对象处理,通过对象属性对网页内容进行操作
2,一些基础的DOM操作
<1>以下为修改div的操作:
- innerHTML为修改操作
- 对象.style.backgroundColor=‘’ 为修改第一个div的背景颜色
先设置div内容:(在body里面)
错误示范:
正确示范:(就是把以上操作在div后面执行,即在body里面执行) 因为要考虑优先加载的问题
如果将div改为divs就会把所有的div全部改为innerHTML里的内容。
<2>一些div的查找方式:
[1]通过div中id名称查找:,
.
[2]class名称查找:(因为class可以有很多个相同的值,所以需要要求只取其一)
如:,
。
这里0的索引就发挥了取其一的作用。
<3>设计点击事件:
这里以图片数组为例:
1,创造图片数组如:
(这里是我个人的路径)
2,在head内插入形式代码,
<style>
body {
text-align: center;
background-color: #dfdfdf;
}
img {
width: 700px;
height: 870px;
margin-top: 20px;
transition: all 0.3s;
}
.wrap {
position: relative;
width: 700px;
height: 870px;
margin: 0 auto;
}
.left,.right {
width: 52px;
height: 93px;
position: absolute;
}
.left {
background-image: url(images/left.webp);
top: 50%;
}
.right {
right: 0;
background-image: url(./images/right.webp);
top: 50%;
}
.left:hover,
.right:hover {
cursor: pointer;
}
</style>
注意:例如,一定要在文件夹里优先存好相关文件,以上代码可以直接复制使用,不用死记硬背。
3,设计点击提示和中央图片。
<body>
<div class="wrap">
<div class="left" id="left"></div>
<div class="right" id="right"></div>
<img src="路径" alt="" />
</div>
<script>
document.querySelector('.left').onclick=function(){
console.log('左边被点击了')
}
注释;// 或者直接改为left.onclick=function(){
// console.log('左边被点击了')
// }也可以;
document.querySelector('.right').onclick=function(){
console.log('右边被点击了')
}
</script>
4,点击切换图片,思路:改变其src路径(就是img里面的内容)
(1)先设置全局变量index (2)再修改匿名函数的功能
如下修改操作:
<script>
var index=0
document.querySelector('.left').onclick=function(){
console.log('左边被点击了') ;
index--;
document.querySelector('img').src=imgArr[index];
}
document.querySelector('.right').onclick=function(){
console.log('右边被点击了');
index++;
document.querySelector('img').src=imgArr[index];
}
</script>
这里需要考虑index是否为负数或者会不会超过imgArr的长度。做以下修改:
<script>
var index=0;
document.querySelector('.left').onclick=function(){
console.log('左边被点击了') ;
index--;
if(index<0){
index=imgArr.length-1};
document.querySelector('img').src=imgArr[index];
}
document.querySelector('.right').onclick=function(){
console.log('右边被点击了');
index++;
if(index>=imgArr.length){
index=0
};
document.querySelector('img').src=imgArr[index];
}
</script>
易错点:当我们在复制路径或者相对路径时,复制出来的往往是\,"\"容易被识别为转义字符,这就会导致你可能路径没有出错时,往往报查找不到文件的错。这就需要你把所有的\改为/。