likes
comments
collection
share

元素中必知重要属性和方法

作者站长头像
站长
· 阅读数 16

上一篇文章我们学习了 Angular 中自定义 Video 操作,如果读者留意的话,会发现在这篇文章中就开始操作元素的属性 scrollLeft,这是很常用的一样属性。那么还有什么属性和方法比较重要呢?其又代表什么意思呢?下面我们进入主题。

  • className
  • classList
  • clientLeft / clientTop
  • clientWidth / clientHeight
  • scrollLeft / scrollTop
  • Element.getBoundingClientRect()
  • append() / remove()
  • querySelector() / querySelectorAll()
  • scroll()
  • mousedown() / mousemove() / mouseup()
  • touchstart() / touchmove() / touchend()

重要属性

1. className

我们给元素添加样式的其中一个方法就是通过类名,我们也可以直接得到这个元素的类名:

let elementDom = document.getElementById('demo');

elementDom.className === 'active'; // 获取 class
elementDom.className = 'active'; // 赋值 class

2. classList

当然我们也可以获取整个元素的类的列表。

<div id="demo" class="demo1 demo2"></div>
let demo = document.getElementById("demo");
console.log(demo.classList);
// {
//   "0": "demo1",
//   "1": "demo2"
// }

获取到类的列表后,我们可以对其进行 add, remove, replace 等操作,这在我们平常实际开发中很有用处的哦。

3. clientLeft / clientTop

clientLeft 表示元素左边框的宽度,clientTop 表示元素上边框的高度。两者都是只读属性,返回整数数值。

// 用法
let demo = document.getElementById('demo');
demo.clientLeft;
demo.clientHeight:

元素中必知重要属性和方法

4. clientWidth / clientHeight

clientWidth 表示元素的宽度,其宽度包含 content 内容宽度和左右两侧的 padding 值;clientHeight 表示元素的高度,其高度包含 content 内容高度和上下两侧的 padding 值。

// 用法
let demo = document.getElementById('demo');
demo.clientWidth;
demo.clientHeight;

元素中必知重要属性和方法

5. scrollLeft / scrollTop

scrollLeft 表示返回元素水平滚动的像素,以左侧的 left margin 开始算; scrollTop 表示返回元素垂直滚动的像素,以顶侧的 top margin 开始算。

// 用法
let demo = document.getElementById('demo');
demo.scrollLeft;
demo.scrollTop;

元素中必知重要属性和方法

重要方法

1. Element.getBoundingClientRect()

getBoundingClientRect() 方法返回元素的top, right, bottom 和 left是相对视口的位置。

// 用法
let demo = document.getElementById('demo');
demo.getBoundingClientRect()

元素中必知重要属性和方法

你还可以通过这个方法获取元素其左上角顶点相对可视窗口的坐标(x, y)及其元素的宽度和高度~

2. append() / remove()

对元素进行追加 append 和移除 remove

// 用法
let demo = document.getElementById('demo');
let p = document.createElement('p');
p.id = 'demoP';
demo.append(p);

let oEl = document.getElementById('demoP');
demo.remove(pEl);

3. querySelector() / querySelectorAll()

querySelector 方法是对指定的筛选器进行过滤查找元素。我们一般用document.getElementById 获取 document.getElementByClassName 的方法去查找,难免有些作用范围有限,必须有 idclassName

<div id='demo'>
  <p>1</p>
  <p>2</p>
</div>
// 用法
let demo = document.body.querySelector("div#demo");
let demoP = demo.querySelector("p"); // 返回第一个 p 元素
let demoPs = demo.querySelectorAll("p"); // 返回满足条件的 nodeList,这里是全部的 p 元素

4. scroll()

scroll 滚动事件,表示元素滚动到页面特定的坐标 (x-coord, y-coord)

// 用法
let demo = document.getElementById('demo');
demo.scroll({
  top: 100,
  left: 100,
  behavior: 'smooth'
})

scrollIntoView() 也很常用。

5. mousedown() / mousemove() / mouseup()

pc 端的开发中,我们监听用户的事件最后的三个方法,在 Angular 中自定义 Video 操作文章中我们已经使用过。

mousedown 表示你鼠标按下的事件,mousemove 表示鼠标按下并移动,mouseleave 表示鼠标松开。在 mobile 移动端开发的过程中,其对应的是 touchstart() / touchmove() / touchend()

下一篇文章的提及的功能,我们将结合本文讲到的知识点来实现,敬请谅解~

【完】✅