巧用mutationObservable的时机改变样式
hugh 的个人博客 2020-06-03 12:13:57 前端webiframetoast
# 1. 场景
在iframe下,如果线上toast, 通常会有位置问题, 这时候就需要手动计算,但是toast的组件,一般没有event可以监听, 这时候,我们可以利用mutationObservable来监听到当前的toast的状态,从而改变位置
# 2. 使用方法
- 确定toast元素 一般toast元素是复用的, 同时可能出现第一次使用才初始化, 所以可以先校验
let targetNode = document.getElementById('message_container')
if (!targetNode) {
const div = document.createElement('div')
div.id = 'message_container'
document.body.appendChild(div)
targetNode = div
}
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
- 对该目标元素设置监听
// 只需要观察属性和子级变化即可
const config = { attributes: true, childList: true }
// 一旦子级变化,可以确定内容被附加进去, 触发top变更
const callback = function(mutations) {
for (const mutation of mutations) {
console.log(mutation, mutation.target)
if (
mutation.type == 'childList' &&
mutation.target.id === 'message_container'
) {
if (mutation.addedNodes && mutation.addedNodes.length > 0) {
const topScroll = getWindowScrollTop(window.top)
mutation.target.style.top = 16 + topScroll + 'px'
}
}
}
}
// 创建一个观察器实例
const observer = new MutationObserver(callback)
if (targetNode) {
// 启用观察
observer.observe(targetNode, config)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
其中 getWindowScrollTop方法,需要可以获取到父级的变化(域名一致) 域名不一致时,可以通过postMessage通知变更