介绍
通过 jquery
封装水印方法,水印的展现方式为全屏显示 当前日期及自定义水印文字。
实现效果
代码
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
function userWater() {
// div和绝对定位形式
function cssHelper(el, prototype) {
for (let i in prototype) {
el.style[i] = prototype[i]
}
}
// 获取当前时间
const today = new Date();
// 获取当前时间(today)的年份
const year = today.getFullYear().toString().slice(-2);;
// 获取月份
const month = String(today.getMonth() + 1).padStart(2, '0');
// 获取当前日
const day = String(today.getDate()).padStart(2, '0');
// 得到年月日
const thisDayDate = `${year}${month}${day}`; //打印当前日期
const contents = '水印' + thisDayDate; //自定义水印的内容: 文字+当前日期
const tempElement = document.createElement('span');
tempElement.style.visibility = 'hidden';
tempElement.style.display = 'inline-block';
tempElement.style.position = 'absolute';
tempElement.style.whiteSpace = 'nowrap';
tempElement.textContent = contents;
document.body.appendChild(tempElement);
const width = tempElement.offsetWidth;
document.body.removeChild(tempElement);
console.log('Width of contents:', width);
function createItem() {
const item = document.createElement('div')
item.innerHTML = contents
cssHelper(item, {
position: 'absolute',
top: `50px`,
left: `25px`,
fontSize: `14px`,
color: '#000',
lineHeight: 1.5,
opacity: 0.1,
transform: `rotate(-15deg)`,
transformOrigin: '0 0',
userSelect: 'none', // 用户无法选中
whiteSpace: 'nowrap',
})
item.classList.add('box');
return item;
}
function createWater() {
const waterHeight = 80;
const waterWidth = width + 20;
const { clientWidth, clientHeight } = document.documentElement ||
document.body;
// 不能使用ceil向上取整,否则会出现超出一屏的水印
const column = Math.floor(clientWidth / waterWidth);
const rows = Math.floor(clientHeight / waterHeight);
console.log(column,rows,'............',column*rows)
const waterWrapper = document.createElement('div');
waterWrapper.className = 'waterWrapper'
waterWrapper.style.position = 'absolute';
waterWrapper.style.top = '0';
waterWrapper.style.left = '0';
waterWrapper.style.display = 'flex';
waterWrapper.style.flexWrap = 'wrap';
waterWrapper.style.pointerEvents = 'none';
waterWrapper.style.overflow = 'hidden';
waterWrapper.style.boxSizing = 'border-box';
for (let i = 0; i < column * rows; i++) {
const wrap = document.createElement('div');
cssHelper(wrap, Object.create({
position: 'relative',
width: `${waterWidth}px`,
height: `${waterHeight}px`,
flex: `0 0 ${waterWidth}px`,
overflow: 'hidden',
}));
wrap.appendChild(createItem());
waterWrapper.appendChild(wrap)
}
document.body.appendChild(waterWrapper)
}
createWater();
window.onresize = function() {
const wrapper =
document.getElementsByClassName('waterWrapper')[0];
document.body.removeChild(wrapper);
createWater();
}
}
userWater();
</script>
总结
通过定位和对页面高宽的获取,可以实现根据屏幕大小,自定义显示水印 ,进行适配显示。