//获取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;
}

前端js代码以备不时之需的更多相关文章

  1. 通用的前端js代码

    1.判断是否移动设备的浏览器,是否允许触摸事件.(响应式网页) if(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i. ...

  2. 前端js上传文件 到后端接收文件

    下面是前端js代码: <html> <head> <meta http-equiv="Content-Type" content="text ...

  3. IE浏览器如何调试Asp.net的 js代码

    不管我们开发什么项目,都需要使用调试.后端的调试比较简单.前端js调试稍微复杂了一点,但是也别怕,因为我们有很多调试前端js代码的浏览器工具.比如IE浏览器.firefox浏览器.chrome浏览器等 ...

  4. php如何优雅地把数组传递给前端js脚本?

    比如说http://echarts.baidu.com/demo...这个例子中,一般里面的timeData数组都是数据库的所有记录的单独某一个列的集合,而例子中第149行的 data:[ 1,2,3 ...

  5. 爬虫必备:Python 执行 JS 代码 —— PyExecJS、PyV8、Js2Py

    在使用爬虫中,经常会遇到网页请求数据是经过 JS 处理的,特别是模拟登录时可能有加密请求.而目前绝大部分前端 JS 代码都是经过混淆的,可读性极低,想理解代码逻辑需要花费大量时间.这时不要着急使用 S ...

  6. 解读前端js中签名算法伪造H5游戏加分

    信息安全在我们日常开发中息息相关,稍有忽视则容易产生安全事故.对安全测试也提出更高要求.以下是笔者亲自实践过程: 一. 打开某个数钱游戏HTML5页面,在浏览器 F12 开发工具中,查看的js,如下, ...

  7. thinkphp在前端页面的js代码中可以使用 U方法吗? 可以使用模板变量如__URL__等吗?

    thinkphp在前端页面的js代码中可以使用 U方法吗? : 可以的! tp的U方法, 是"全局的", 什么是全局的? 就是, 可以在 "任何地方"使用的: ...

  8. 工欲善其事 之 Web 前端调试工具格式化混淆过的 JS 代码

    工欲善其事 之 Web 前端调试工具格式化混淆过的 JS 代码 太阳火神的漂亮人生 (http://blog.csdn.net/opengl_es) 本文遵循"署名-非商业用途-保持一致&q ...

  9. jeecg中ajax传值的前端js和后台代码

    前端js: var b=1; $.ajax({ type : "POST", --Post请求方式 url : 'orderController.do?wuliao', --路径 ...

随机推荐

  1. mod_rewrite是Apache的一个非常强大的功能

    mod_rewrite是Apache的一个非常强大的功能,它可以实现伪静态页面.下面我详细说说它的使用方法!对初学者很有用的哦! 1.检测Apache是否支持mod_rewrite 通过php提供的p ...

  2. 操作实践,git本地分支执行rebase,让主干分支记录更简洁

    声明:迁移自本人CSDN博客https://blog.csdn.net/u013365635 我们平时在写代码的时候,难免会修修改改,如果团队中每个人的代码提交记录都包含着一堆中间过程,是很不利于团队 ...

  3. 干货 | CDN搭配OSS最佳实践 ——搭建动静态分离的应用架构

    一.传统架构及痛点 传统的网站产品应用架构,所有资源部署在应用服务器本地存储或挂载的数据存储区,对于动静态资源不作分离, 产品架构如下图所示: 该架构存在诸多问题: ● 系统性能会随着系统访问量的增长 ...

  4. 吴裕雄--天生自然深度学习TensorBoard可视化:监控指标可视化

    import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data # 1. 生成变量监控信息并定义生 ...

  5. Problem for Nazar CodeForces - 1151C (前缀和)

    Problem for Nazar Nazar, a student of the scientific lyceum of the Kingdom of Kremland, is known for ...

  6. Bless All

    # php code $i = 2333 $myJXOI = JXOI() while($i == 2333){ ++myJXOI.score , ++myJXOI.rp , --myJXOI.常数 ...

  7. docker安装文档

    Docker离线安装以及本地yum源构建http://blog.csdn.net/joniers/article/details/64122820http://blog.csdn.net/wsscy2 ...

  8. 学习spring第二天

    Spring第二天笔记 1. 使用注解配置Spring入门 1.1. 说在前面 学习基于注解的IoC配置,大家脑海里首先得有一个认知,即注解配置和xml配置要实现的功能都是一样的,都是要降低程序间的耦 ...

  9. 20190221 beautiful soup 入门

    beautiful soup 入门 Beautiful Soup 是 python 的一个库,最主要的功能是从网页抓取数据. Beautiful Soup 自动将输入文档转换为 Unicode 编码, ...

  10. [原]livekd使用问题记录

    sysinternal suite中的livekd.exe可谓神器.可以用来观察本地内核的一些状态,当然抓内核dump再合适不过了. 在使用livekd的时候遇到了一些问题,现总结如下: 使用live ...