「1 分鐘學 DOM 基礎操作」添加和移除元素樣式、添加至元素內、添加和移除事件、計算鼠標相對元素的位置

大家好,今天我們來花 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);
你可能注意到,我們將事件名稱當做函數(shù)參數(shù)傳遞給事件綁定函數(shù)。
四、計算鼠標在元素內的相對位置
要計算鼠標點擊事件,鼠標在元素內的相對位置,我們需要用到 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)實現(xiàn)對象的私有屬性
1分鐘用 CSS + HTML 實現(xiàn)個按字母吸附滑動的列表(類似手機通訊錄列表)
「1分鐘學JS基礎」移除最后一個字符、Promise.allSettled()的使用、日期數(shù)組排序
評論
圖片
表情
