前端js代码以备不时之需

//获取id元素信息
let getId = (args) => {
return document.getElementById(args);
}

//获取类名元素
let getClassName = (args) => {
if (document.getElementsByClassName) {
if (document.getElementsByClassName(args).length != 1) {
return document.getElementsByClassName(args);
} else {
return document.getElementsByClassName(args)[0];
}
} else {
//可以准确找到dom元素 影响性能
for (let i = 0; i < document.getElementsByTagName("div").length; i++) {
if (document.getElementsByTagName("div")[i].getAttribute("class") === args) {
return document.getElementsByTagName("div")[i];
}
}
}
}

/* 获取动态样式*/
function getStyle(element, alt) {
return parseInt((element.currentStyle ? element.currentStyle : window.getComputedStyle(element, "null"))[alt]);
}

//阻止默认事件阻止冒泡事件
let mrEvent = (e) => {
let eve = e || window.event;
eve.stopPropagation ? eve.stopPropagation() : window.event.cancelBubble = true;
eve.preventDefault ? eve.preventDefault() : window.event.returnValue = false;
}

/**
*
* 设置响应式字体和缩放比例时间戳
*
*/
let fontSize = () => {
const scale = 1 / window.devicePixelRatio; //设置缩放比例
document.querySelector('meta[name=viewport]').setAttribute('content', 'width=device-width,initial-scale=' + scale + ',maximum-scale=' + scale + ',minimum-scale=' + scale + ',user-scalable=no');
document.documentElement.style.fontSize = document.documentElement.clientWidth / 10 + 'px'; //设置文档字体大小
}

//app & pc 移动端浏览器访问网址 修改
let IsPc = () => {
if (navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/webOS/i) || navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/iPod/i) || navigator.userAgent.match(/BlackBerry/i) || navigator.userAgent.match(/Windows Phone/i)) {
return true;
  window.location.href='http://m.jingyanshequ.com';
} else {
return false;
 window.location.href='http://www.jingyanshequ.com'
}
}

// 正则表达式

let regPass = /^[a-zA-Z0-9\~\'\!\@\#\¥\$\%\^\&\*\(\)\-\+\_\=\:\.]{6,10}$/;  //匹配字符数字特殊字符  qwe123***

js定义开关 切换开关的办法false 取反 或者自加1÷2求余是否被整除

/*修改头像剪裁上传*/
let uploadPhoto = () =>{

let photoCircle = getId('previewCircle'),
previewShear = getId('previewShear'),
ctx = photoCircle.getContext("2d"),
ctx2 = previewShear.getContext("2d"),
file = null,reader,
previewPhoto = getId('previewPhoto');
photoCircle.width="80";
photoCircle.height="80";
previewShear.width="500";
previewShear.height="500";

function canFun(x,y){
let top = !y ? 0: parseInt(y);
let left= !x ? 0: parseInt(x);
ctx.clearRect(0,0,80,80);
ctx.save();
ctx.arc(40,40,40,0*Math.PI,2*Math.PI);
ctx.clip();
ctx.drawImage(previewPhoto,top*0.4,left*0.4,80,80);
ctx2.clearRect(0,0,500,500);
ctx2.drawImage(previewPhoto,top*2.5,left*2.5,250,250,0,0,500,500);
}

//鼠标按下范围框 判断鼠标是否移动 是否抬起 抬起则取消鼠标按下事件

$('#chooseBox').mousedown(function(e){
mrEvent(e);
let oEvent = e || event,
originX = e.clientX,
originY = e.clientY,
left = 0,top = 0;
window.onmousemove = function(e){
mrEvent(e);
top = e.clientY - originY,
left = e.clientX - originX;
$('#chooseBox').css({left: left,top: top});
if ($('#chooseBox').position().left <= 0) {
left = 0;
$('#chooseBox').css({left: left,});
}
if ($('#chooseBox').position().left > 120) {
left = '120px'
$('#chooseBox').css({left: left});
}
if ($('#chooseBox').position().top <= 0) {
top = 0;
$('#chooseBox').css({top: top});
}
if ($('#chooseBox').position().top > 120) {
top = '120px'
$('#chooseBox').css({top: top});
}
canFun(top,left);
}
window.onmouseup = function(e){
mrEvent(e);
window.onmousemove = null;
return ;
}
});

function changeFile(){
$('.chooseBox').css({display:'block',left:0,top:0});
file = $(this)[0].files[0];
reader = new FileReader();
let width = getStyle(previewPhoto,"width");
let height = getStyle(previewPhoto,"height");
reader.onload = function(e){
previewPhoto.setAttribute('src',e.target.result);
canFun();
}
reader.readAsDataURL(file);
}
$("input[type='file']").change(changeFile);
}

//canvas 刮奖效果

function Lottery(id, cover, coverType, width, height, drawPercentCallback) {
this.conId = id;
this.numR = null;
this.conNode = document.getElementById(this.conId);
this.cover = cover;
this.coverType = coverType;
this.background = null;
this.backCtx = null;
this.mask = null;
this.maskCtx = null;
this.lottery = null;
this.lotteryType = 'image';
this.width = width || 60;
this.height = height || 30;
this.clientRect = null;
this.drawPercentCallback = drawPercentCallback;
}

Lottery.prototype = {
createElement: function (tagName, attributes) {
var ele = document.createElement(tagName);
for (var key in attributes) {     //按照对象方式设置属性
ele.setAttribute(key, attributes[key]);
}
return ele;
},
getTransparentPercent: function(ctx, width, height) {
var imgData = ctx.getImageData(0, 0, width, height),
pixles = imgData.data,
transPixs = [];
for (var i = 0, j = pixles.length; i < j; i += 4) {
var a = pixles[i + 3];
if (a < 128) {
transPixs.push(i);
}
}
return (transPixs.length / (pixles.length / 4) * 100).toFixed(2);
},
resizeCanvas: function (canvas, width, height) {
canvas.width = width;
canvas.height = height;
canvas.getContext('2d').clearRect(0, 0, width, height);
},
drawPoint: function (x, y) {
this.maskCtx.beginPath();
var radgrad = this.maskCtx.createRadialGradient(x, y, 0, x, y, 30);
radgrad.addColorStop(0, 'rgba(0,0,0,0.6)');
radgrad.addColorStop(1, 'rgba(255, 255, 255, 0)');
this.maskCtx.fillStyle = radgrad;
this.maskCtx.arc(x, y, 30, 0, Math.PI * 2, true);
this.maskCtx.fill();
if (this.drawPercentCallback) {
this.drawPercentCallback.call(null, this.getTransparentPercent(this.maskCtx, this.width, this.height));
}
},
bindEvent: function () {
var _this = this;
var device = (/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(navigator.userAgent.toLowerCase()));
var clickEvtName = device ? 'touchstart' : 'mousedown';
var moveEvtName = device? 'touchmove': 'mousemove';
if (!device) {
var isMouseDown = false;
document.addEventListener('mouseup', function(e) {
isMouseDown = false;
}, false);
} else {
document.addEventListener("touchmove", function(e) {
if (isMouseDown) {
e.preventDefault();
}
}, false);
document.addEventListener('touchend', function(e) {
isMouseDown = false;
}, false);
}
this.mask.addEventListener(clickEvtName, function (e) {
isMouseDown = true;
var docEle = document.documentElement;
if (!_this.clientRect) {
_this.clientRect = {
left: 0,
top:0
};
}
var x = (device ? e.touches[0].clientX : e.clientX) - _this.clientRect.left + docEle.scrollLeft - docEle.clientLeft;
var y = (device ? e.touches[0].clientY : e.clientY) - _this.clientRect.top + docEle.scrollTop - docEle.clientTop;
_this.drawPoint(x, y);
}, false);

this.mask.addEventListener(moveEvtName, function (e) {
if (!device && !isMouseDown) {
return false;
}
var docEle = document.documentElement;
if (!_this.clientRect) {
_this.clientRect = {
left: 0,
top:0
};
}
var x = (device ? e.touches[0].clientX : e.clientX) - _this.clientRect.left + docEle.scrollLeft - docEle.clientLeft;
var y = (device ? e.touches[0].clientY : e.clientY) - _this.clientRect.top + docEle.scrollTop - docEle.clientTop;
_this.drawPoint(x, y);
}, false);
},
drawLottery: function () {
this.background = this.background || this.createElement('canvas', {
style: 'position:absolute;left:0;top:0;'
});
this.mask = this.mask || this.createElement('canvas', {
style: 'position:absolute;left:0;top:0;'
});

if (!this.conNode.innerHTML.replace(/[\w\W]| /g, '')) {
this.conNode.appendChild(this.background);
this.conNode.appendChild(this.mask);
this.clientRect = this.conNode ? this.conNode.getBoundingClientRect() : null;
this.bindEvent();
}

this.backCtx = this.backCtx || this.background.getContext('2d');
this.maskCtx = this.maskCtx || this.mask.getContext('2d');

if (this.lotteryType == 'image') {
this.numR= Math.floor(Math.random()*9000)+1000;
this.resizeCanvas(this.background, this.width, this.height);
this.drawMask();
this.backCtx.fillStyle = "#008b8b";
this.backCtx.fillRect(0, 0, this.width, this.height);
this.backCtx.font="20px Script";
this.backCtx.strokeStyle = "#fff";
this.backCtx.strokeText(this.numR,10,22);
} else if (this.lotteryType == 'text') {
this.width = this.width;
this.height = this.height;
this.resizeCanvas(this.background, this.width, this.height);
this.backCtx.save();
this.backCtx.fillStyle = '#FFF';
this.backCtx.fillRect(0, 0, this.width, this.height);
this.backCtx.restore();
this.backCtx.save();
var fontSize = 30;
this.backCtx.font = 'Bold ' + fontSize + 'px Arial';
this.backCtx.textAlign = 'center';
this.backCtx.fillStyle = '#F60';
this.backCtx.fillText(this.lottery, this.width / 2, this.height / 2 + fontSize / 2);
this.backCtx.restore();
this.drawMask();
}
},
drawMask: function() {
this.resizeCanvas(this.mask, this.width, this.height);
if (this.coverType == 'color') {
this.maskCtx.fillStyle = this.cover;
this.maskCtx.fillRect(0, 0, this.width, this.height);
this.maskCtx.globalCompositeOperation = 'destination-out';
} else if (this.coverType == 'image'){
var image = new Image(),
_this = this;
image.onload = function () {
_this.maskCtx.drawImage(this, 0, 0);
_this.maskCtx.globalCompositeOperation = 'destination-out';
}
image.src = this.cover;
}
},
init: function (lottery, lotteryType) {
this.lottery = lottery;
this.lotteryType = lotteryType || 'image';
this.drawLottery();
return this.numR;
}
}


const lottery = () =>{
let registerLottery = new Lottery('registerLotteryContainer', '#CCC', 'color', 60, 30);
let loginLottery = new Lottery('loginLotteryContainer', '#CCC', 'color', 60, 30);
registerResultYZM = registerLottery.init();
loginResultYZM = loginLottery.init();
}

图片瀑布流

动态创建图片元素当鼠标滚动到某一位置符合条件我请求数据动态添加元素信息 

let docHeight = window.document.body.scrollHeight,    //获取文档高度
eleTop = window.scrollY || window.document.documentElement.scrollTop || document.body.scrollTop, //滚动条高度
eleHeight = window.document.getElementsByClassName("picture")[0].getElementsByTagName("li")[0].offsetHeight, //容器高度
scrollTop = docHeight - eleTop - 2.5*eleHeight -100;  // 文档高度 - 滚动条滚动高度 -  容器高度 
if(scrollTop < 146.5){
_this.getWaterFall();  //调用服务器的数据信息 创建dom元素信息
}

//评论时间展示
const modifyMessage = (args)=>{

let nd = upload.publishTime().split(' ')[0],
nt = upload.publishTime().split(' ')[1],
nyear = parseInt(nd.split('-')[0]),
nmounth = parseInt(nd.split('-')[1]),
nday = parseInt(nd.split('-')[2]),
nhour = parseInt(nt.split(':')[0]),
nminute = parseInt(nt.split(':')[1]),
nseconds = parseInt(nt.split(':')[2]),
pd,pt,pyear,pmounth,pday,phour,pminute,pseconds;

for(let i = 0 ; i < args.length ; i++){
pd = args[i].arctile_publishTime.split(' ')[0],
pt = args[i].arctile_publishTime.split(' ')[1],
pyear = parseInt(pd.split('-')[0]),
pmounth = parseInt(pd.split('-')[1]),
pday = parseInt(pd.split('-')[2]),
phour = parseInt(pt.split(':')[0]),
pminute = parseInt(pt.split(':')[1]),
pseconds = parseInt(pt.split(':')[2]);
if(nyear - pyear > 0){
args[0].arctile_publishTime = nyear-pyear+" 年前";
}else if(nmounth - pmounth > 0){
args[0].arctile_publishTime = nmounth - pmounth+" 个月前";
}else if(nday-pday > 0){
args[0].arctile_publishTime = nday-pday+" 天前";
}else if(nhour-phour > 0){
args[0].arctile_publishTime = nhour-phour+" 小时前";
}else{
args[0].arctile_publishTime = nminute-pminute+" 分钟前";
}
}
return args;
}

//vue 分页

page: function () { // 总页数
return Math.ceil(this.total / this.display);
},
grouplist: function () { // 获取分页页码
var len = this.page, temp = [], list = [], count = Math.floor(this.pagegroup / 2), center = this.current;
if (len <= this.pagegroup) {
while (len--) {
temp.push({text: this.page - len, val: this.page - len});
}
;
return temp;
}
while (len--) {
temp.push(this.page - len);
}
;
var idx = temp.indexOf(center);
(idx < count) && ( center = center + count - idx);
(this.current > this.page - count) && ( center = this.page - count);
temp = temp.splice(center - count - 1, this.pagegroup);
do {
var t = temp.shift();
list.push({
text: t,
val: t
});
} while (temp.length);
if (this.page > this.pagegroup) {
(this.current > count + 1) && list.unshift({text: '...', val: list[0].val - 1});
(this.current < this.page - count) && list.push({text: '...', val: list[list.length - 1].val + 1});
}
return list;
}

猜你喜欢

转载自www.cnblogs.com/qiaoxinming/p/9284410.html