Day2 DOM元素的操作

2.1 操作元素样式属性

1.通过 JS 设置/修改标签元素的样式属性

  • 比如通过轮播图小圆点自动更换颜色样式

  • 点击按钮可以滚动图片这是移动的图片的位置 left 等等

2.通过 style 属性操作 CSS

1.语法:

html 复制代码
<!DOCTYPE html>
<html lang="en">
​
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- 为盒子设置初始样式 -->
<style>
.box {
width: 300px;
height: 300px;
margin: 50px auto;
background-color: antiquewhite;
}
</style>
</head>
​
<body>
<!-- 定义一个盒子 -->
<div class="box"></div>
<script>
// 获取元素
const box = document.querySelector('.box')
// 修改样式属性 对象.style.样式属性 = '值'  需要跟单位,如px
box.style.width = '600px'
// 遇到多组单词,使用小驼峰命名法
box.style.backgroundColor = 'hotpink'
</script>
</body>
​
</html>

2.注意:

  • 修改样式通过 style 属性引出

  • 如果属性有 - 连接符,需要转换为小驼峰命名法

  • 赋值的时候,需要的时候不能忘记加CSS单位

3.案例:页面刷新,随机更换背景图片

html 复制代码
<!DOCTYPE html>
<html lang="en">
​
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>刷新背景图片</title>
    <style>
          /* css样式 */
        body {
            background-image: url(../11.8/homework/1.webp);
        }
    </style>
</head>
​
<body>
    <script>
        /*
        需求:当我们刷新页面,页面中的背景图片随机显示不同的图片
        分析:
            1.需要使用随机函数
            2.css页面背景图片 background-image
            3.标签选择body,因为body是唯一的标签,可以直接写document.body,style
        */
        let num = Math.floor(Math.random() * 21)
        document.body.style.backgroundImage = `url(../11.8/homework/${num}.webp)`
    </script>
</body>
​
</html>

3.操作类名(className)操作CSS

1.如果修改的样式比较多,直接通过style属性修改比较繁琐,我们可以通过借助于CSS类名的形式

2.语法:

html 复制代码
<!DOCTYPE html>
<html lang="en">
​
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>className</title>
<style>
/* 原始样式 */
div {
   width: 200px;
   height: 200px;
   margin: 60px auto;
   background-color: aqua;
}
​
/* className待用样式,注意:调用后只会覆盖重复的,不会删除原始样式 */
.box {
   width: 600px;
   height: 600px;
   background-color: pink;
}
</style>
</head>
​
<body>
<div></div>
<script>
// className语法
// 1.获取元素
const div = document.querySelector('div')
// 2.添加类名
div.className = 'box'
// 3.如果原本元素有class属性,需要保留
div.className = '初始class名 新增的class名'
</script>
</body>
​
</html>

3.注意:

  • 由于class是关键字,所以使用className去代替

  • className是使用新值换旧值,如果需要添加一个类,需要保留之前的类名

2.2 this指向
  • 在事件处理函数中,this指向事件源

  • 在全局作用域下,this指向window

html 复制代码
<body>
  <div class="box">点击我这个盒子吧</div>
  <button>按钮</button>
  <script>
    let box = document.querySelector('.box')
    let btn = document.querySelector('button')
    box.onclick = function () {
      this.style.width = '100px'
      this.style.height = '100px'
      this.style.backgroundColor = 'pink'
    }
    // 错误使用
    btn.onclick = function () {
      // 这里的this指的是按钮
      this.style.width = '100px'
      this.style.height = '100px'
      this.style.backgroundColor = 'pink'
    }
  </script>
</body>
2.3 通过className添加样式
  • 语法:元素对象.className='新类名 旧类名'

    通过className添加的是类名,该类名是已经存在的,会覆盖原来的类名,所以要把原来的类名一起写进去

    html 复制代码
    <!DOCTYPE html>
    <html lang="en">
    ​
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Document</title>
      <style>
        .box {
          width: 100px;
          height: 100px;
          color: skyblue;
          background-color: pink;
        }
    ​
        .new {
          background-color: grey;
        }
      </style>
    </head>
    ​
    <body>
      <div class="box">旋风小子</div>
      <script>
        let box = document.querySelector('.box')
        let flag = true
        box.onclick = function () {
          if (flag) {
            this.className = 'new box'
            flag = !flag
          } else {
            this.className = 'box'
            flag = !flag
          }
        }
      </script>
    </body>
    ​
    </html>
2.4 排他操作
  • js分同步和异步

    排他思想:清楚全部样式,在给自己添加样式

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <ul>
    <li>111</li>
    <li>222</li>
    <li>333</li>
    <li>444</li>
    <li>555</li>
    <li>666</li>
  </ul>
  <script>
    let li=document.querySelectorAll('li')
    for(let i=0;i<li.length;i++){
      li[i].onclick=function(){
        for(let j=0;j<li.length;j++){
            // 清楚全部样式                 
          li[j].style.backgroundColor=''
        }
           // 给自己添加样式
        this.style.backgroundColor='green'
      }
    }
  </script>
</body>
</html>
2.5 自定义属性的获取和设置
  • 获取自定义属性-----元素.getAttribute('自定义属性名'),自定义属性名怎么写就怎么拿,可以获取元素自带的属性

  • 设置自定义属性-----元素.setAttribute('自定义属性名','值')

  • 移除自定义属性-----元素.removeAttribute('自定义属性名')

  • 自己定义属性时,统一为data-xxx=' '

html 复制代码
<!DOCTYPE html>
<html lang="en">
​
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    img{
      width: 300px;
    }
  </style>
</head>
​
<body>
  <div class="box" index="1" date-name="自定义属性值"></div>
  <img src="../images/轮播图1.jpg" alt="">
  <script>
    /* 
    自定义属性的获取和设置
    */
    let box = document.querySelector('.box')
    let img=document.querySelector('img')
    // 获取自定义属性-----元素.getAttribute('自定义属性名'),自定义属性名怎么写就怎么拿,可以获取元素自带的属性
    console.log(box.getAttribute('index'))  //1
    console.log(box.getAttribute('date-name'))  //自定义属性值
    // 设置自定义属性-----元素.setAttribute('自定义属性名','值')
    img.setAttribute('设置的自定义属性名','自定义属性值')
    // 移除自定义属性-----元素.removeAttribute('自定义属性名')
    img.removeAttribute('设置的自定义属性名')
  </script>
</body>
​
</html>
2.6 常用的事件
  • onblur:失去焦点

    onchange:内容发生改变

    onfocus:内容改变

    oninput:内容变化就会触发

    html 复制代码
    <!DOCTYPE html>
    <html lang="en">
    ​
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Document</title>
    </head>
    ​
    <body>
      <input type="text">
      <div>输入的姓名是:
        <span>我是span</span>
      </div>
      <script>
        let ipt = document.querySelector('input')
        let span = document.querySelector('span')
        let div=document.querySelector('div')
        // 
        /* ipt.onblur = function () {
          span.innerText = ipt.value
        } */
        // 
        /* ipt.onchange = function () {
          console.log('onchange')
        } */
        // 
        /* ipt.onfocus = function () {
          console.log('onfocus')
        } */
        // 
        /* ipt.oninput = function (e) {
          console.log('oninput')
          console.log(e.target.value);
        } */
    ​
        div.onclick=function(e){
          // 触发谁拿到的就是谁
          console.log(e.target)
          // this指向事件源
          console.log(this)
        }
      </script>
    </body>
    ​
    </html>

    onkeydown:键盘按下

    onkeypress:键盘按下

    onkeyup:键盘弹起

    html 复制代码
    <body>
      <input type="text">
      <script>
        let ipt=document.querySelector('input')
        /* window.onkeydown=function(e){
          // enter的键码是13
          console.log(e.keyCode)
          if(e.keyCode==13){
            ipt.focus()
          }
        } */
        window.onkeyup=function(e){
          console.log(e.keyCode)
        }
      </script>
    </body>

    onmousedown:鼠标按下

    onmouseenter:鼠标进入

    onmouseleave:鼠标离开

    onmousemove:鼠标移动

    onmouseout:鼠标即将离开

    onmouseup:鼠标弹起

    onscroll:滚动

    onsubmit:提交

var和let的区别:
  • 作用域不同

    var是函数作用域(伪全局作用域)

    let是块级作用域:在块级作用域内声明的变量无法在块级作用域外面使用

  • let不能在定义之前访问该变量,但是var可以在定义之前访问(let不会预解析)

    javascript 复制代码
    console.log(a)//预解析只声明不复制 undefined
    var a = 10//var 后面的变量,变量提升了(也就是预解析了)
    console.log(a)//10
    console.log(b)//报错(Uncaught ReferenceError: Cannot access 'b' before initialization),let声明的变量不能在定义(初始化)之前访问
    let b = 20
  • let不能被重新定义,但是var是可以的

javascript 复制代码
let a = 10
let a = "你好"//报错(Uncaught SyntaxError: Identifier 'a' has already been declared)let后面的变量不能重新定义,var可以
console.log(a)
var b = 10
var b = "你好"
console.log(b)
相关推荐
叁分之一37 分钟前
“我打包又失败了”
前端·npm
tang游戏王12338 分钟前
AJAX进阶-day4
前端·javascript·ajax
无语听梧桐42 分钟前
vue3中使用Antv G6渲染树形结构并支持节点增删改
前端·vue.js·antv g6
如影随从43 分钟前
04-ArcGIS For JavaScript的可视域分析功能
开发语言·javascript·arcgis·可视域分析
go2coding1 小时前
开源 复刻GPT-4o - Moshi;自动定位和解决软件开发中的问题;ComfyUI中使用MimicMotion;自动生成React前端代码
前端·react.js·前端框架
freesharer1 小时前
Zabbix 配置WEB监控
前端·数据库·zabbix
web前端神器1 小时前
forever启动后端服务,自带日志如何查看与设置
前端·javascript·vue.js
才艺のblog1 小时前
127还是localhost....?
javascript·https·浏览器特性
是Yu欸1 小时前
【前端实现】在父组件中调用公共子组件:注意事项&逻辑示例 + 将后端数组数据格式转换为前端对象数组形式 + 增加和删除行
前端·vue.js·笔记·ui·vue
今天是 几 号2 小时前
WEB攻防-XSS跨站&反射型&存储型&DOM型&标签闭合&输入输出&JS代码解析
前端·javascript·xss