1)复习:
案例:返回顶部
案例:吸顶效果
案例: 选项卡
案例:全选反选
2)事件(这三个事件是直接挂在window对象下)
1)window.onload 页面资源加载完后(包含图片),再执行JS
2)window.onresize 窗口变化触发的事件(响应式会用到)
3)window.onscroll 滚动条事件
遗忘:
3. innerHTML 只解析标签里面的【内容】
innerText 既解析标签 也解析内容 【原样输出】
3.1遗忘自定义属性
附加:自定义标签?
【自定义属性】
CSS样式
*[ bd = 'red']{
color: red;
}
HTML布局
<标签 bd='red'>
1、attributes 获取对象的所有属性【重要】
1.1【显示】标签属性的方法**(property是属性的意思)
a.标签的自有属性 ele.property oImg.alt
b.标签的自定义属性 ele.getAttribute(property) oImg.getAttribute('alt
')
1.2 【设置】标签的属性
a.标签的自有属性 ele.property oImg.alt = '拼命加载中
’
b/标签的自定义属性 ele.setAttribute(property,value) oImg.setAttribute('alt','拼命加载中')
1.3【移除】属性**
ele.removeAttribute(property) ele.removeAttribute('index')
2、样式
2.1 style.cssText
只能获取CSS样式
2.2 getComputedStyle(ele)[属性]
既可以获取JS样式 也可以获取CSS样式
3、className属性
使用名称className而不是class作为属性名,是因为【“class” 】在JavaScript中是个保留字.
1) classList 获取类名列表
2)remove() 删除某一个类名
3)add() 添加一个类名
4)replace(old,new) 用新的替换旧的
案例:选项卡
案例:全选和反选
案例:选项卡
.active {
background: red;
}
div {
display: none;
}
.show {
display: block;
}
<button>1</button>
<button>2</button>
<button>3</button>
<div>1</div>
<div>2</div>
<div>3</div>
<script>
// 出错点:setAttribute('index', i)语法规范
// 1、获取元素
var btns = document.querySelectorAll('button');
console.log(btns);
var divs = document.querySelectorAll('div');
console.log(divs);
// 2、循环为每一个按钮注册点击事件
for (var i = 0; i < btns.length; i++) {
// 【给按钮绑定自定义属性index 为了找到被点击的按钮所对应的角标】!!!
btns[i].setAttribute('index', i); //自定义属性是为了找div才设置的
btns[i].onclick = function () {
// 遍历得到每一个按钮
for (var j = 0; j < btns.length; j++) {
console.log(btns.length)
btns[j].setAttribute('class', '');
divs[j].setAttribute('class', ''); //为社么div也写在这里 因为跟btn数组长度一样
}
this.setAttribute('class', 'active');
var v = this.getAttribute('index'); //这里是获取元素属性【 getAttribute】 而不是设置元素属性【setAttribute】
divs[v].setAttribute('class', 'show');
}
}
</script>
案例:全选和反选
全选:<input type="checkbox" id="checkAll"> <br>
选项:<input type="checkbox" class="checkOne">
<input type="checkbox" class="checkOne">
<input type="checkbox" class="checkOne">
<input type="checkbox" class="checkOne">
<script>
// 获取元素
var chkAll = document.querySelector('#checkAll');
var chkOne = document.querySelectorAll('.checkOne');
console.log(chkOne, chkAll)
// 【全选】
chkAll.onclick = function () {
// 判断全选有没有被选中
if (chkAll.checked == true) {
// 如果选中了 那么选项都被选了
for (var i = 0; i < chkOne.length; i++) {
chkOne[i].checked = true;
}
} else {
for (var i = 0; i < chkOne.length; i++) {
chkOne[i].checked = false;
}
}
}
// 【反选】
/*先循环遍历--后注册点击事件*/
for (var i=0;i<chkOne.length;i++){
chkOne[i].onclick = function(){
// 反选的话 我们需要知道用户选中几个,所以需要一个计数器
var count = 0;
// 那么如何知道选中几个,需要遍历才知道
for(var j = 0;j<chkOne.length;j++){
// 如果有选中 就加1
if(chkOne[j].checked){
count++;
}
}
// 通过判断chkOne的长度。全选的话chkAll.checked就是true 否则就是false
if(count==chkOne.length){
chkAll.checked=true;
}else{
chkAll.checked=false;
}
}
}
</script>