1、querySelector() 获取文档中 id="demo" 的元素
<p id="demo">id="demo" 的 p 元素</p>
<button onclick="myFunction()">点我</button>
<script>
function myFunction() {
document.querySelector("#demo").innerHTML = "Hello World!";
}
</script>
2、获取文档中第一个 <p> 元素:
<script>
function myFunction() {
document.querySelector("p").style.backgroundColor = "red";
}
</script>
3、获取文档中 class="example" 的第一个元素:
<script>
function myFunction() {
document.querySelector(".example").style.backgroundColor = "red";
}
</script>
4、获取文档中 class="example" 的第一个 <p> 元素:
<script>
function myFunction() {
document.querySelector("p.example").style.backgroundColor = "red";
}
</script>
5、获取文档中有 "target" 属性的第一个 <a> 元素,并且为这个带有 target 属性的a链接添加红色背景。
<script>
function myFunction() {
document.querySelector("a[target]").style.border = "10px solid red";
}
</script>
6、以下实例演示了多个选择器的使用方法。假定你选择了两个选择器: <h2> 和 <h3> 元素。
以下代码将为文档的第一个 <h2> 元素添加背景颜色:
<h2> h2 元素</h2>
<h3> h3 元素</h3>
<script>
document.querySelector("h2, h3").style.backgroundColor = "red";
</script>
7、但是,如果文档中 <h3> 元素位于 <h2> 元素之前,<h3> 元素将会被设置指定的背景颜色。
<h3> h3 元素</h3>
<h2> h2 元素</h2>
<script>
document.querySelector("h2, h3").style.backgroundColor = "red";
</script>
8、示例:
<script>
var swiper = new Swiper(".mySwiper", {
spaceBetween: 10,
navigation: {
nextEl: ".swiper-button-next",
prevEl: ".swiper-button-prev",
},
slidesPerView: 4,
freeMode: true,
watchSlidesProgress: true,
on: {
click: function(e){
let index = e.clickedIndex
console.log(index)
let video1 = document.querySelector("#mymousdown")
let video2 = document.querySelector("#mymousdown2")
if(index === 0){
video1.play()
video2.play()
}else{
video1.pause()
video2.pause()
}
}
}
});
</script>
9、完结。-------------------------------------------------------------------------------------------------------------------