index.html
index.css
#water-mark {
pointer-events: none;
// 元素永远不会成为鼠标事件的target,解决水印覆盖在最上方,导致下层元素,无法执行鼠标事件
}
span {
display: inline-block;
width: 200px;
transform: rotate(-15deg);
position: absolute;
}
index.js
window.onload = function () {
let waterMark = document.getElementById('water-mark');
// MutationObserver 只会监听到内联样式的修改, 所以要把可能会导致水印看不见的相关样式写成内联样式
waterMark.style.cssText = `
position: fixed;
top: 0;
left: 0;
bottom: 0;
right: 0;
background: rgba(0,0,0,.1);
`;
for (let i = 0; i < 8; i++) {
for (let j = 0; j < 10; j++) {
let span = document.createElement('span');
span.innerText = '这是水印';
span.style.top = 150 * i + 'px';
span.style.left = 200 * j + 'px';
span.style.display = 'inline-block';
span.style.opacity = 1;
span.style.color = 'rgba(0,0,0,.2)';
waterMark.append(span)
}
// 这里与上方设置内联样式不一致,是为了让自己方便记忆两种设置的方法
}
const config = {childList: true, subtree: true, attributeFilter: ['style']};
const callback = function (mutationsList) {
for (let mutation of mutationsList) {
if (// 这个if是判断这三种情况是修改了跟水印相关的DOM元素,其他的都是跟水印无关的
mutation.target.id === 'water-mark' // 改变的DOM样式属性的是id为water-mark的元素
|| (mutation.removedNodes[0] && mutation.removedNodes[0].id === 'water-mark') // 装载水印的DOM被移除
|| mutation.target.offsetParent.id === 'water-mark' // 修改的当前元素是water-mark的子元素
) {
console.log('水印被动了, 这里可以执行一下水印被动了之后的逻辑');
if (mutation.type === 'childList') {
console.log('A child node has been added or removed.');
} else if (mutation.type === 'attributes') {
console.log('The ' + mutation.attributeName + ' attribute was modified.');
}
}
}
};
const observer = new MutationObserver(callback);
//MutationObserver 只会监听子元素的删除,监听不到本身, 所以要添加的父元素上进行监听
let container = document.getElementById('container');
observer.observe(container, config);
};
这是我当初做这个需求是遇到的问题,后来在高人的指点下解决了,为了加深自己的印象和今后方便回忆,就专门自己实现了一下,如果大家发现有什么地方不正确或者有更好的方法实现,欢迎大家留言区留言。