效果
代码图片
代码
window.waterMark = function (config) {var defaultConfig = {content: `我是水印`,fontSize: '16px',opacity: 0.3,rotate: '-15',color: '#ADADAD',modalId: 'J_waterMarkModalByXHMAndDHL',};config = Object.assign({}, defaultConfig, config);var existMarkModalDom = document.getElementById(config.modalId);if (existMarkModalDom) {document.body.removeChild(existMarkModalDom);}var markModalDom = document.createElement('div');markModalDom.setAttribute('id', config.modalId);markModalDom.style['position'] = 'fixed';markModalDom.style['top'] = 0;markModalDom.style['left'] = 0;markModalDom.style['bottom'] = 0;markModalDom.style['right'] = 0;markModalDom.style['background-color'] = 'transparent';markModalDom.style['pointer-events'] = 'none';markModalDom.style['z-index'] = 9999;markModalDom.style['overflow'] = 'hidden';var markContentDom = document.createElement('span');markContentDom.style['position'] = 'relative';markContentDom.style['display'] = 'inline-block';markContentDom.style['max-width'] = '33%';markContentDom.style['min-width'] = '400px';markContentDom.style['padding'] = '80px 0';markContentDom.style['height'] = '100px';markContentDom.style['text-align'] = 'center';markContentDom.style['opacity'] = config.opacity;markContentDom.style['pointer-events'] = 'none';var markContentTxtDom = document.createElement('span');markContentTxtDom.innerHTML = config.content;markContentTxtDom.style['position'] = 'absolute';markContentTxtDom.style['display'] = 'inline-block';markContentTxtDom.style['pointer-events'] = 'none';markContentTxtDom.style['top'] = '50%';markContentTxtDom.style['left'] = '80%';markContentTxtDom.style['transform'] = 'translate(-50%, -50%) rotate(' + config.rotate + 'deg)';markContentTxtDom.style['font-size'] = config.fontSize;markContentTxtDom.style['color'] = config.color;markContentDom.appendChild(markContentTxtDom);var contentHtml = markContentDom.outerHTML;var allContentHtml = '';for (var i = 0; i < 100; i++) {allContentHtml += contentHtml;}markModalDom.innerHTML = allContentHtml;document.body.appendChild(markModalDom);
};
使用方法
- components文件夹下创建Watermark文件夹
- Watermark文件夹下创建index.js文件
- 将以上代码粘贴进去
-
在项目入口文件引入 import './components/Watermark/index'
-
直接调用 waterMark() //全局加水印
操作完看看效果吧!!!
注:本人前端小白 ,如有不对的地方还请多多指教