文章目录
一、定义属性的操作1.获取属性值2.设置元素属性值3. 移除属性
选项卡案例二、H5自定义属性设置H5自定义属性获取H5自定义属性
一、定义属性的操作
1.获取属性值
element.属性; 获取属性值. : 获取内置属性值 (元素本身自带的属性)element.getAttribute(‘属性’); : 主要获得自定义的属性
var div = document.querySelector('div');
console.log(div.id); // div
console.log(div.getAttribute('index')); // 1
2.设置元素属性值
element.属性 = 值; 修改元素属性值 element.setAttribute('属性', '值'); 修改自定义属性值.
var div = document.querySelector('div');
console.log(div.id); // div
console.log(div.getAttribute('index')); // 1
div.id = 'dddd'
console.log(div.id); // dddd
div.setAttribute('index', '2');
console.log(div.getAttribute('index')); // 2
3. 移除属性
element.removeAttribute('属性');
var div = document.querySelector('div');
div.removeAttribute('index');
console.log(div.getAttribute('index')); // null
选项卡案例
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
a {
color: black;
}
li {
list-style: none;
}
.ETab {
position: relative;
width: 990px;
}
.box {
width: 100%;
height: 50px;
font-size: 14px;
/* background-color: #ccc; */
border-bottom: 1px solid red;
overflow: hidden;
margin-bottom: 50px;
}
.box .current {
background-color: red;
color: #fff;
}
.box ul li {
float: left;
height: 50px;
text-align: center;
padding: 0px 25px;
line-height: 50px;
}
.boxs {
position: absolute;
font-size: 12px;
}
.box1 ul li {
width: 50%;
padding-left: 42px;
}
.box ul a:hover {
color: red;
}
.box1 {
padding-top: 20px;
margin-top: 50px;
margin-bottom: 50px;
}
.box2 ul li {
float: left;
width: 200px;
padding-left: 42px;
line-height: 20px;
}
.boxs1 {
position: absolute;
}
.item {
display: none;
}
- 商品介绍
- 规格与包装
- 售后保障
- 商品评价
- 品牌: Apple
- 商品名称:AppleiPhone 12
- 商品编号:100016034400
- 商品毛重:350.00g
- CPU型号:其他
- 运行内存:其他
- 机身存储:128GB
- 摄像头数量:后置双摄
- 后摄主摄像素:1200万像素
- 前摄主摄像素:1200万像素
- 屏幕比例:其他
- 分辨率:其他
- 屏幕前摄组合:其他
- 操作系统:iOS(Apple)
规格与包装
售后保障
商品评价
// 点击变化背景色
var boxli = document.querySelectorAll('.box ul li');
var items = document.querySelectorAll('.tab_con .item');
for (var i = 0; i < boxli.length; i++) {
boxli[i].setAttribute('index', i);
boxli[i].onclick = function () {
for (var i = 0; i < boxli.length; i++) {
if (i == 0) {
boxli[i].className = 'boxs';
}
boxli[i].className = '';
}
this.className = 'current';
// 点击切换内容
for (var i = 0; i < items.length; i++) {
items[i].style = 'display: none;';
}
var index = this.getAttribute('index');
items[index].style = 'display: block;';
}
}
二、H5自定义属性
设置H5自定义属性
H5规定自定义属性data- 开头作为属性名并赋值.
比如 :
获取H5自定义属性
var div = document.querySelector('div');
console.log(div.getAttribute('data-index')); // 1
// h5新增获取自定义属性
console.log(div.dataset.index); // 1
console.log(div.dataset['index']); // 1
dataset 是一个集合, 里面存放了所有以data开头的自定义属性.