01.自定义属性
1.自定义属性:
作用:保存数据 通用的自定义属性的前缀 data-属性="属性值"
注:自定义的属性不能通过 元素.属性 取属性值 ,需使用getAttribute();
2.自定义属性的获取
元素.getAttribute('data-url');
3.设置
节点.setAttribute('属性名称','修改后的属性值'); (修改后的属性值是一个变量的时候,不加引号)
4.删除
元素.removeAttribute('data-url');
简单测试:
<img src="./images/1.jpg" alt="" data-url="./images/a.jpg">
//获取自定义属性:
var oImg = document.querySelector('img');
console.log(oImg.getAttribute('data-url'));
//设置自定义属性
var oImg = document.querySelector('img');
oImg.setAttribute('data','ddddd');
//删除
var oImg = document.querySelector('img');
oImg.removeAttribute('data-url');
02.自定义属性案例
鼠标滑过,切换图片
<style>
*{
margin:0;
paddin:0;
}
.showImg{
300px;
height:300px;
border:1px solid red;
}
.showImg img{
display:block;
100%;
height:100%;
}
.btnImg{
300px;
height:60px;
border:1px solid red;
}
.btnImg img{
60px;
height:60px;
display:block;
float:left;
cursor:pointer;
}
</style>
<section class="showImg">
<img src="./images/rose1.jpg" alt="">
</section>
<div class="btnImg">
<img src="./images/rose1.jpg" alt="">
<img src="./images/rose2.jpg" alt="">
<img src="./images/rose3.jpg" alt="">
<img src="./images/rose4.jpg" alt="">
<img src="./images/rose5.jpg" alt="">
</div>
<script>
//鼠标滑过事件 onmouseover
//如果获取的是一个节点集合,并且给每一个元素绑定事件,需要遍历
var aImg = document.querySelector('.showImg img');
var bigImg = document.querySelectorAll('btnImg img');//获取到的是一个节点的集合
for(var i = 0 ; i < bigImg.length ; i++){ //循环遍历,给每一个img绑定鼠标滑过事件
//循环遍历,绑定事件(重点)
bigImg[i].onmouseover = function(){
//鼠标滑过每一个img的时候,获取它的src的值,直接更改大图的src
aImg.src = this.src; //上面显示的图片的src就是在遍历时,获取的当前图片的src
var src = this.getAttribute('src'); //获取当前图片的src
aImg.setAttribute('src',src); //将设置显示区,显示当前图片的src
}
}
<