//获取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. nginx调整large_client_header_buffers

    https://nginx.org/en/docs/http/ngx_http_core_module.html#large_client_header_buffers Syntax: large_c ...

  2. 2.Jenkins结合k8s完成Jenkins slave功能

    1.构建镜像 下载基础镜像,这里使用openvz的包,下载地址为:https://wiki.openvz.org/Download/template/precreated,下载centos7的镜像 下 ...

  3. 题解 P6004 【[USACO20JAN]Wormhole Sort S】

    这题真的是非常标准的模板题啊 看到连最少的边,第一时间会想到 \(kruskal\) .这道题的难点其实就一个:你要注意到连边权最大的边使整个图联通 为什么:题意是第i个点想走到 \(pos[i]\) ...

  4. oracle 学习(三)pl/sql语言函数

    系统内置函数 数学运算函数 字符串函数 统计函数 日期函数 用户定义函数:存储在数据库中的代码块,可以把值返回到调用程序.调用时如同系统函数一样 参数模式 IN模式:表示该参数时输入给函数的参数 OU ...

  5. springboot打包,jar包可以以service方式启动

    <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> ...

  6. SVN的import和export的使用

    import 上传到服务器 export 下载到本地 import这个命令在使用的时候,都要多加一级目录 比如 目录结构是 E:\\1\\2  在1目录下执行import  只会把2目录提交上去,1的 ...

  7. Hibernate(四)--延迟加载(lazyload)

    hibernate中的延迟加载(lazyload)分属性的延迟加载和关系的延迟加载 属性的延迟加载: 当使用load的方式来获取对象的时候,只有访问了这个对象的属性,hibernate才会到数据库中进 ...

  8. iOS 中UITableView的深理解

    例如下图:首先分析一下需求:1.根据模型的不同状态显示不同高度的cell,和cell的UI界面. 2.点击cell的取消按钮时,对应的cell首先要把取消按钮隐藏掉,然后改变cell的高度. 根据需求 ...

  9. BTree

    hash.平衡二叉树.BTree.B+tree的区别 https://blog.csdn.net/qq_40673786/article/details/90082444 联合索引在B+树上的结构介绍 ...

  10. Java之接口(java8的新特性)

    public class SubClassTest { public static void main(String[] args) { SubClass s = new SubClass(); // ...