css选择器本质就是css与html两种语法建立关联的特定标识符那在JS语言的语法中,也有特点的方式与html语言编写的表情建立关联,我们就称之为JS选择器。
一、getElement系列
// 1.通过id名获取唯一满足条件的页面元素
document.getElementById('id名');
// 该方法只能由document调用
// 2、通过class名获取所有满足条件的页面元素
document.getElementsByClassName('class名');
// 该方法可以由document及任意页面元素对象调用
// 返回值为HTMLCollection (一个类数组结果的对象,使用方式同数组)
// 没有匹配到任何结果返回空HTMLCollection对象 ([])
// 3.通过tag名获取所有满足条件的页面元素
document.getElementsByTagName('tag名');
// 该方法可以由document及任意页面元素对象调用
// 返回值为HTMLCollection (一个类数组结果的对象,使用方式同数组)
// 没有匹配到任何结果返回空HTMLCollection对象 ([])
二、querySelect系列
// 1.获取第一个匹配到的页面元素
document.querySelector('css3语法选择器');
// 该方法可以由document及任意页面对象调用
// 2.获取所有匹配到的页面元素
document.querySelectorAll('css3语法选择器');
// 该方法可以由document及任意页面对象调用
// 返回值为NodeList (一个类数组结果的对象,使用方式同数组)
// 没有匹配到任何结果返回空NodeList对象 ([])
2.1 案例:
<body>
<div id="box" class="box"></div>
<script>
var box1 = document.getElementById('box');
var box2 = document.querySelector('.box');
// box1 === box2,就代表页面id为box,class为box的div标签
</script>
</body>
三、JS页面操作
3.1 鼠标事件
/*
交互的方式,叫做标签对象的事件绑定,可以绑定的事件有:
onclick:鼠标点击
ondblclick:鼠标双击
onmousedown:鼠标按下
onmousemove:鼠标移动
onmouseup:鼠标抬起
onmouseover:鼠标悬浮
onmouseout:鼠标移开
oncontextmenu:鼠标右键
*/
3.2 事件的绑定
// 具体绑定事件的方式:
<body>
<div class="box">绑定点击事件后可以完成点击交互</div>
<script>
var box = document.querySelector('.box');
// 页面class为box的div被鼠标点击后会有弹出框
box.onclick = function() {
alert("box标签被点击了")
}
</script>
</body>
3.3 操作行间试样式
<head>
<style>
.box {
width: 200px;
height: 200px;
}
</style>
</head>
<body>
<div class="box" style="background-color: red"></div>
<script>
var box = document.querySelector('.box');
// 语法:页面对象.全局style属性.具体的样式名
box.onclick = function() {
// 读:获取行间式样式值
var bgColor = box.style.backgroundColor;
// 写:对行间式样式进行赋值,初始没有该条行间式样式,相同会自动添加设置好的行间式
box.style.backgroundColor = 'orange'; // css3多个单词的属性名采用小驼峰命名法
}
</script>
</body>
3.4 只读计算后 样式
<head>
<style>
.box {
width: 200px;
height: 200px;
}
</style>
</head>
<body>
<div class="box" style="background-color: red"></div>
<script>
var box = document.querySelector('.box');
// 语法:getComputedStyle(页面元素对象, 伪类).样式名;
// 注:我们不需要考虑伪类的范畴,直接用null填充即可
box.onclick = function() {
// 只读:获取计算后样式值
var width = getComputedStyle(box, null).width;
}
</script>
</body>
3.5 操作标签class名
<body>
<div class="box">class名操作</div>
<script>
var box = document.querySelector('.box');
// 查看类名
var cName = box.className;
// 修改类名
box.className = "ele";
// 增加类名
box.className = " tag"; // 添加后的结果class="ele tag",所以赋值时一定注意tag前有个空格字符串
// 删除所有类名
box.className = "";
</script>
</body>
3.6 操作标签全局属性值
<body>
<img src="https://www.baidu.com/favicon.ico" class="image" />
<script>
var img = document.querySelector('.image');
// 查看全局属性值
var imgSrc = img.getAttribute('src');
// 修改全局属性值
img.setAttribute('src', 'img/bg_logo.png');
// 删除全局属性值
img.setAttribute = ('src', '');;
</script>
</body>
评论 (0)