80 行 JS 代码实现页面添加水印:文字水印、多行文字水印、图片水印、文字&图片水印
warning:
这篇文章距离上次修改已过189天,其中的内容可能已经有所变动。
以下是实现页面添加水印的示例代码,包括文字水印、多行文字水印、图片水印和文字与图片混合水印。
// 文字水印
function addTextWatermark(text) {
const watermarkDiv = document.createElement('div');
watermarkDiv.innerText = text;
watermarkDiv.style.position = 'fixed';
watermarkDiv.style.bottom = '10px';
watermarkDiv.style.right = '10px';
watermarkDiv.style.color = 'rgba(0, 0, 0, 0.2)';
watermarkDiv.style.zIndex = '1000';
document.body.appendChild(watermarkDiv);
}
// 多行文字水印
function addMultilineTextWatermark(texts) {
const watermarkDiv = document.createElement('div');
watermarkDiv.style.position = 'fixed';
watermarkDiv.style.bottom = '10px';
watermarkDiv.style.right = '10px';
watermarkDiv.style.color = 'rgba(0, 0, 0, 0.2)';
watermarkDiv.style.zIndex = '1000';
texts.forEach((text, index) => {
const lineDiv = document.createElement('div');
lineDiv.innerText = text;
lineDiv.style.marginBottom = index === texts.length - 1 ? '0' : '10px';
watermarkDiv.appendChild(lineDiv);
});
document.body.appendChild(watermarkDiv);
}
// 图片水印
function addImageWatermark(imageSrc) {
const watermarkDiv = document.createElement('div');
const img = document.createElement('img');
img.src = imageSrc;
watermarkDiv.style.position = 'fixed';
watermarkDiv.style.bottom = '10px';
watermarkDiv.style.right = '10px';
watermarkDiv.style.zIndex = '1000';
watermarkDiv.appendChild(img);
document.body.appendChild(watermarkDiv);
}
// 文字与图片混合水印
function addTextAndImageWatermark(text, imageSrc) {
const watermarkDiv = document.createElement('div');
const textDiv = document.createElement('div');
const img = document.createElement('img');
textDiv.innerText = text;
img.src = imageSrc;
watermarkDiv.style.position = 'fixed';
watermarkDiv.style.bottom = '10px';
watermarkDiv.style.right = '10px';
watermarkDiv.style.color = 'rgba(0, 0, 0, 0.2)';
watermarkDiv.style.zIndex = '1000';
watermarkDiv.appendChild(textDiv);
watermarkDiv.appendChild(img);
document.body.appendChild(watermarkDiv);
}
// 使用示例
addTextWatermark('版权所有');
addMultilineTextWatermark(['版权所有', '所有权利归xxx所有']);
addImageWatermark('watermark.png');
addTextAndImageWatermark('版权所有', 'watermark.png');
这段代码提供了四个函数,每个函数负责添加一种类型的水印。使用时直接调用相应的函数,并传入所需的水印文本或图片路径即可。这些水印会被添加到页面的底部右侧,并且可以通过CSS样式调整位置、大小和透明度。
评论已关闭