一.操作元素常用属性
通过JS设置/修改标签元素属性,比如通过src更换图片
最常见的属性比如:href、title、src等
语法:
对象.属性 = 值<body> <img src="../images/1.jpeg" alt=""> <script> const img = document.querySelector('img'); img.src = '../images/2.jpeg'; img.title = '这是一张图片'; </script> </body>案例:
刷新页面,随机展示一张图片
<body> <img src="../images/1.jpeg" alt=""> <script> function getNumber(N,M){ return Math.floor(Math.random()*(M-N+1)+N); } const img = document.querySelector('img'); const random = getNumber(1,3); img.src = `../images/${random}.jpeg`; </script> </body>二.通过style修改样式属性
语法:
对象.style.样式属性 = 值<style> .box{ width: 100px; height: 100px; background-color: red; } </style> <body> <div class="box"></div> <script> const box = document.querySelector('.box'); box.style.width = '200px'; box.style.backgroundColor = 'blue'; //小驼峰命名法 box.style.border = '5px solid yellow'; </script> </body>1.修改样式通过style属性引出
2.如果属性有-连接符,需要转换为小驼峰命名法
3.赋值的时候,需要的时候不要忘记加css单位
三.通过类名修改样式
如果修改的样式比较多,直接通过style属性修改比较繁琐,我们可以通过借助于css类名的形式
语法:
元素.className = 'active' //active是一个css类名1.由于class是关键字,所以使用className去代替
2.className是使用新值换旧值,如果需要添加一个类,需要保留之前的类名
<style> div{ width: 100px; height: 100px; background-color: red; } .box{ width: 200px; height: 200px; background-color: blue; border: 5px solid yellow; } </style> <body> <div></div> <script> const div = document.querySelector('div'); div.className = 'box'; </script> </body>四.通过classList修改样式
为了解决className 容易覆盖以前的类名,我们可以通过classList方式追加和删除类名
语法:
//追加一个类 元素.classList.add('类名') //删除一个类 元素.classList.remove('类名') //切换一个类 元素.classList.toggle('类名')<style> .box{ width: 100px; height: 100px; color: black; } .active{ color: red; background-color: blue; } </style> <body> <div class="box">哈哈哈</div> <script> const box = document.querySelector('.box'); box.classList.add('active'); </script> </body>五.随机轮播图
刷新页面,页面中的轮播图会显示不同图片以及样式
<style> .box{ width: 600px; height: 400px; border: 1px solid; } .slider{ width: 100%; height: 100%; position: relative; } .slider img{ width: 100%; height: 100%; position: absolute; top: 0; left: 0; } .footer{ width: 100%; height: 50px; position: absolute; bottom: 50px; left: 20px; display: flex; } .footer li{ width: 8px; height: 8px; border-radius: 50%; background-color: #333; margin: 0 10px; list-style: none; } .footer li.active{ background-color: #fff; } </style> <body> <div class="box"> <div class="slider"> <img src="../images/1.jpeg" alt=""> </div> <div class="footer"> <li></li> <li></li> <li></li> </div> </div> <script> // 轮播图数据 const sliderData = [ { url: '../images/1.jpeg', title: '这是第一张图片' }, { url: '../images/2.jpeg', title: '这是第二张图片' }, { url: '../images/3.jpeg', title: '这是第三张图片' } ] // 随机数 const randomNum = parseInt(Math.random() * sliderData.length); console.log(sliderData[randomNum]); // 随机数对应的图片数据 const img = document.querySelector('.slider img'); img.src = sliderData[randomNum].url; const circle = document.querySelector(`.footer li:nth-child(${randomNum + 1})`); console.log(circle); circle.classList.add('active'); </script> </body>