<div id="box" class="wrap container">hi,there.</div>
const body = document.body const div = document.createElement('div') div.textContent = 'hi,there.' body.prepend(div) body.append('from glpla')
const dom = document.getElementById('box');
const dom = document.getElementsByClassName('wrap'); const dom = document.getElementsByClassName('wrap container');
const dom = document.getElementsByTagName('div');
const dom = document.querySelector('#box');
const dom = document.querySelectorAll('.wrap');
function fn(el) { return document.querySelector(el) }
document.addEventListener('eventName', () => { console.log('xxx'); })
.页面加载完毕,包括DOM解析完毕和脚本文件下载完毕并执行,但是不会等样式文件、图片和其它资源都加载完毕
.window 的 load 事件则是完全加载 - 所有资源都加载完毕
.所以 DOMContentLoaded 事件比 load 事件更早触发
document.addEventListener('DOMContentLoaded', () => { console.log('document ready'); }) window.addEventListener('load', () => { console.log('window loaded'); })
document.addEventListener('scroll', function () { console.log('scrolling'); }) document.addEventListener('scrollend', function () { console.log('end'); })
document.addEventListener('scroll', () => { back2top.classList.toggle('active', scrollY > innerHeight) })
.hidden { overflow: hidden; }
ham.addEventListener('click', function () { //... ... document.body.classList.toggle('hidden') })
.当一个元素进入或退出全屏模式时,会触发 fullscreenchange 事件 - F11全屏模式
.事件首先被发送给正在过渡到全屏模式或从全屏模式退出的元素
.然后冒泡事件到 document,所以 document 可以监听该事件
.单纯的切换全屏模式并不会触发该事件
<div class="wrap"> <div class="switch-btn">Fullscreen</div> </div>
const fullScreenElement = document.querySelector('.wrap'); const btn = document.querySelector('.switch-btn'); btn.addEventListener('click', () => { if (document.fullscreenElement) { document.exitFullscreen(); } else { fullScreenElement.requestFullscreen(); } }) document.addEventListener('fullscreenchange', () => { if (document.fullscreenElement) { console.log("Entered fullscreen mode."); } else { console.log("Leaving fullscreen mode."); } })
.全屏事件异常时触发
.针对文档内容的操作
.事件的原始目标是 元素 Element,可以在捕获或冒泡阶段响应并处理
document.addEventListener('copy', (e) => { e.preventDefault() }) document.addEventListener('paste', (e) => { e.preventDefault() })