JS的DOM&Timer

0 阅读2分钟

一、DOM

1、元素对象的获取

  • document.getElementById("")
  • document.getElementsByTagName("")
  • document.querySelectorAll()
  • document.querySelector()
<div id="app">Hello</div>
<div class="box">World</div>
<span class="box">!</span>
// 1. 通过 ID(最快)
const app = document.getElementById('app'); // 返回 <div id="app">

// 2. 通过标签名(返回 HTMLCollection,实时更新)
const divs = document.getElementsByTagName('div'); 
console.log(divs.length); // 2
// divs.forEach 会报错!必须转为数组: Array.from(divs).forEach(...)

// 3. CSS选择器 - 取第一个
const firstBox = document.querySelector('.box'); // 返回 <div class="box">(只取第一个)

// 4. CSS选择器 - 取全部(返回 NodeList,静态)
const allBoxes = document.querySelectorAll('.box'); 
console.log(allBoxes.length); // 2
allBoxes.forEach(el => console.log(el)); // 可以直接遍历,推荐这种写法

//或者根据已有元素对象获取其他元素对象
const cur = document.querySelector('.box');

//获取当前元素的兄弟元素
const next = cur.nextElementSibling
const pre = cur.previousElementSibing

//获取当前元素的父亲、孩子元素
const parent = cur.parentNode
const child = cur.children

2、元素对象的操作

2.1、元素的样式处理

  • 直接设置元素style
  • 切换元素使用的css
1、直接设置元素的style
var element = document.querySelector('.box')
// 驼峰命名法(CSS属性中的 - 要换成驼峰)
element.style.backgroundColor = 'red';
element.style.fontSize = '20px';
element.style.marginTop = '10px';
// 带单位的必须加单位字符串
element.style.width = '100px';

2、切换/替换元素的css:
2.1 element.classList.add/remove/toggle/('类名')
2.2 element.className('类名') - 直接覆盖原类型
<!DOCTYPE html>
<html>
<head>
  <style>
    .box {
      width: 200px;
      height: 200px;
      border: 2px solid #333;
      transition: all 0.3s ease;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 16px;
    }

    /* 定义不同状态样式 */
    .active {
      background: #4CAF50;
      color: white;
      border-radius: 20px;
      transform: scale(1.1);
      box-shadow: 0 4px 15px rgba(76, 175, 80, 0.4);
    }

    .warning {
      background: #ff9800;
      color: white;
      border-color: #e65100;
      font-weight: bold;
    }

    .big {
      width: 300px;
      height: 300px;
      font-size: 24px;
    }

    .rounded {
      border-radius: 50%;
    }
  </style>
</head>
<body>
  <div id="box" class="box">点击按钮切换样式</div>
  
  <button id="toggleActive">切换激活状态</button>
  <button id="toggleWarning">切换警告状态</button>
  <button id="toggleBig">切换大尺寸</button>
  <button id="resetBtn">重置样式</button>

  <script>
    const box = document.getElementById('box');

    // 1. 切换 active 类(经典用法)
    document.getElementById('toggleActive').addEventListener('click', function() {
      box.classList.toggle('active');
    });

    // 2. 切换 warning 类(同时可以添加多个)
    document.getElementById('toggleWarning').addEventListener('click', function() {
      box.classList.toggle('warning');
    });

    // 3. 切换 big 类
    document.getElementById('toggleBig').addEventListener('click', function() {
      box.classList.toggle('big');
      // 同时也可以添加其他类
      // box.classList.toggle('rounded');
    });

    // 4. 重置:移除所有类,只保留 box
    document.getElementById('resetBtn').addEventListener('click', function() {
      box.className = 'box'; // 直接覆盖
      // 或者逐个移除
      // box.classList.remove('active', 'warning', 'big', 'rounded');
    });

    // 5. 检查类是否存在
    console.log('是否有 active 类:', box.classList.contains('active'));

    // 6. 类列表遍历
    box.classList.forEach(className => {
      console.log('当前类:', className);
    });
  </script>
</body>
</html>

3、文字处理

  • element.innerHTML = '处理的文本

    被处理的文本

    '
  • element.innerText = '纯文本'

4、事件

  • element.addEventListener('事件', function(){}):不会出现覆盖的情况
<input id="search" placeholder="搜索...">
<button id="btn">提交</button>
<div id="result"></div>

<script>
  const search = document.getElementById('search');
  const btn = document.getElementById('btn');
  const result = document.getElementById('result');

  // 1. 实时输入监听
  search.addEventListener('input', (e) => {
    result.textContent = `输入中: ${e.target.value}`;
  });

  // 2. 回车提交
  search.addEventListener('keydown', (e) => {
    if (e.key === 'Enter') {
      console.log('按了回车,提交搜索');
    }
  });

  // 3. 点击提交
  btn.addEventListener('click', () => {
    console.log('提交:', search.value);
  });

  // 4. 失去焦点时校验
  search.addEventListener('blur', () => {
    if (search.value.length < 2) {
      alert('至少输入2个字符');
    }
  });
</script>

5、定时器

  • setTimeOut(function(){}, time):一次执行
  • setInterval(function(){}, time):多次执行,清除使用clearInterval(对象)
<div>
  <p>倒计时: <span id="countdown">10</span></p>
  <button id="startBtn">开始</button>
  <button id="stopBtn">停止</button>
</div>

<script>
  const countdownEl = document.getElementById('countdown');
  const startBtn = document.getElementById('startBtn');
  const stopBtn = document.getElementById('stopBtn');
  
  let timer = null;
  let count = 10;

  function startCountdown() {
    // 防止重复开启
    if (timer) return;
    
    count = 10;
    countdownEl.textContent = count;
    
    timer = setInterval(() => {
      count--;
      countdownEl.textContent = count;
      
      if (count <= 0) {
        clearInterval(timer);
        timer = null;
        alert('倒计时结束!');
      }
    }, 1000);
  }

  function stopCountdown() {
    if (timer) {
      clearInterval(timer);
      timer = null;
      console.log('已停止');
    }
  }

  startBtn.addEventListener('click', startCountdown);
  stopBtn.addEventListener('click', stopCountdown);
</script>