「1 分钟学 DOM 基础操作」添加和移除元素样式、添加至元素内、添加和移除事件、计算鼠标相对元素的位置

前端达人

共 1770字,需浏览 4分钟

 ·

2021-11-19 22:08

大家好,今天我们来花 1 分钟来学习 DOM 相关的基础操作,内容虽然简单,但是还是有必要归纳总结的,希望这些整理对大家有所帮助。

一、添加或移除样式

1、添加相关样式至对应 DOM 元素

注意:如果添加多个样式至 DOM 元素,IE11 不兼容。

ele.classList.add('class-name');

// Add multiple classes (Not supported in IE 11)
ele.classList.add('another''class''name');

2、从 DOM 元素中移除样式

注意:同样在DOM元素中移除多个样式,IE11 不兼容。

ele.classList.remove('class-name');

// Remove multiple classes (Not supported in IE 11)
ele.classList.remove('another''class''name');

3、切换 DOM 中指定的样式

ele.classList.toggle('class-name');

二、将元素添加至指定的DOM元素内的末尾

将 ele 元素添加至 target 元素内的末尾

target.appendChild(ele);

三、添加和移除事件

1、使用 ON 属性添加事件(不推荐)

你可以在 dom 元素使用  on{eventName} 的属性,eventName 代表事件名,代码如下:

ele.onclick = function({
    ...
};

// Remove the event handler
delete ele.onclick;

不推荐这种方法,主要是因为很容易造成事件覆盖的问题。

2、使用 addEventListener 方法

const handler = function({
    ...
};

// Attach handler to the `click` event
ele.addEventListener('click', handler);

// Detach the handler from the `click` event
ele.removeEventListener('click', handler);

你可能注意到,我们将事件名称当做函数参数传递给事件绑定函数。

四、计算鼠标在元素内的相对位置

要计算鼠标点击事件,鼠标在元素内的相对位置,我们需要用到 getBoundingClientRect() 这个关键的方法,示例代码如下:

ele.addEventListener('mousedown'function (e{
    // Get the target
    const target = e.target;

    // Get the bounding rectangle of target
    const rect = target.getBoundingClientRect();

    // Mouse position
    const x = e.clientX - rect.left;
    const y = e.clientY - rect.top;
});

总结

由于时间原因,今天分享的 DOM 基础操作专题就分享到这里,感谢你的阅读。

参考:https://github.com/1milligram/html-dom

更多1分钟专题

1分钟搞懂什么是 JS 代理对象(proxies)

1分钟学会如何用 JS 对象代理(proxies)实现对象的私有属性

1分钟学会 2 个复制文本到剪贴板的方法

1分钟学会如何用 JS 计算文本的宽度

1分钟学会个通用妙招,让你知道用户看了啥

1分钟用 CSS + HTML 实现个按字母吸附滑动的列表(类似手机通讯录列表)

「1分钟学JS基础」移除最后一个字符、Promise.allSettled()的使用、日期数组排序

浏览 54
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报