利用js在页面中添加水印

2024年12月14日 建站教程

功能介绍:利用js在页面中添加水印,下面给大家简单介绍一下具体实现代码!

具体实现代码如下:

function water() {
  const watermarkText = '我谁水印'; // 水印文字内容
  const wrap = document.querySelector('#water-box'); //先在html中定义div id="water-box"
  const html = document.querySelector('html');
  const body = document.querySelector('body');
  html.style.margin = "0"
  html.style.padding = "0"
  body.style.margin = "0"
  body.style.padding = "0"
  wrap.style.width = "100vw"
  wrap.style.height = "100vh"
  wrap.style.display = "flex"
  wrap.style.position = "absolute"
  wrap.style.zIndex = "999999"
  wrap.style.flexDirection = "row"
  wrap.style.justifyContent = "space-around"
  wrap.style.flexWrap = "wrap"
  wrap.style.pointerEvents = "none"
  wrap.style.fontSize = "16px"
  wrap.style.color = "rgba(184, 184, 184, 0.6)"
  wrap.style.overflow = "hidden"

  const wrapWidth = wrap.offsetWidth; // 容器的宽度
  const wrapHeight = wrap.offsetHeight; // 容器的高度

  const tempSpan = document.createElement('span');
  tempSpan.innerText = watermarkText;
  tempSpan.style.visibility = 'hidden';
  document.body.appendChild(tempSpan);
  const watermarkWidth = tempSpan.getBoundingClientRect().width + 160; // 水印文本的实际宽度
  const watermarkHeight = tempSpan.getBoundingClientRect().height + 120; // 水印文本的实际高度
  document.body.removeChild(tempSpan);

  const numCols = Math.floor(wrapWidth / watermarkWidth); // 计算每行可容纳的方格数量
  const numRows = Math.floor(wrapHeight / watermarkHeight); // 计算可容纳的行数

  for (let i = 0; i < numRows; i++) {
    for (let j = 0; j < numCols; j++) {
      const watermark = document.createElement('div');
      watermark.classList.add('watermark');
      watermark.innerText = watermarkText;
      watermark.style.padding = "60px 80px"
      watermark.style.transform = "rotate(-45deg)"
      watermark.style.transformOrigin = "center center"
      wrap.appendChild(watermark);
    }
  }
}

本文链接:http://so.lmcjl.com/news/19563/

展开阅读全文
相关内容