JS实现水印
前段时间因项目有个需求需要在页面加上水印,查了一下资料,网上介绍的方法大都都是通过背景图片实现的,而我想通过div实现。
CSS样式
.watermark{
opacity: 0.4;
position: fixed;
height: 45px;
width: 160px;
transform: rotate(315deg);
-ms-transform: rotate(315deg);
-moz-transform: rotate(315deg);
-webkit-transform: rotate(315deg);
-o-transform: rotate(315deg);
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
pointer-events: none;
}
.watermark p{
color: #dcdcdc;
}
js
/**
* 水印
* @param userName
*/
function createWaterMark(name){
if(!name){
return ;
}
var width = document.body.clientWidth;
var height = document.body.clientHeight;
var len = width/80;
len = len.toFixed(0);
var hen = height/80;
hen = hen.toFixed(0);
var init_top = 30;
var dif_heigth = 0;
if(height<1000){
dif_heigth = height/3;
}else {
dif_heigth = height/8;
}
for(var j=0;j<hen;j++){
for(var i=0;i<4;i++){
var div =document.createElement("div");
var p = document.createElement("p");
p.innerHTML = name+getCurDate();
div.setAttribute("class","watermark");
div.style.marginLeft = (20+(i*width/4))+"px";
div.style.top = (init_top+j*dif_heigth)+"px";
div.appendChild(p);
document.body.appendChild(div);
}
}
}
//获取当前日期
function getCurDate() {
var date = new Date();
var seperator1 = "-";
var month = date.getMonth() + 1;
var strDate = date.getDate();
if (month >= 1 && month <= 9) {
month = "0" + month;
}
if (strDate >= 0 && strDate <= 9) {
strDate = "0" + strDate;
}
var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate;
return currentdate;
}