前端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;
}
前端js代码以备不时之需的更多相关文章
- 通用的前端js代码
1.判断是否移动设备的浏览器,是否允许触摸事件.(响应式网页) if(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i. ...
- 前端js上传文件 到后端接收文件
下面是前端js代码: <html> <head> <meta http-equiv="Content-Type" content="text ...
- IE浏览器如何调试Asp.net的 js代码
不管我们开发什么项目,都需要使用调试.后端的调试比较简单.前端js调试稍微复杂了一点,但是也别怕,因为我们有很多调试前端js代码的浏览器工具.比如IE浏览器.firefox浏览器.chrome浏览器等 ...
- php如何优雅地把数组传递给前端js脚本?
比如说http://echarts.baidu.com/demo...这个例子中,一般里面的timeData数组都是数据库的所有记录的单独某一个列的集合,而例子中第149行的 data:[ 1,2,3 ...
- 爬虫必备:Python 执行 JS 代码 —— PyExecJS、PyV8、Js2Py
在使用爬虫中,经常会遇到网页请求数据是经过 JS 处理的,特别是模拟登录时可能有加密请求.而目前绝大部分前端 JS 代码都是经过混淆的,可读性极低,想理解代码逻辑需要花费大量时间.这时不要着急使用 S ...
- 解读前端js中签名算法伪造H5游戏加分
信息安全在我们日常开发中息息相关,稍有忽视则容易产生安全事故.对安全测试也提出更高要求.以下是笔者亲自实践过程: 一. 打开某个数钱游戏HTML5页面,在浏览器 F12 开发工具中,查看的js,如下, ...
- thinkphp在前端页面的js代码中可以使用 U方法吗? 可以使用模板变量如__URL__等吗?
thinkphp在前端页面的js代码中可以使用 U方法吗? : 可以的! tp的U方法, 是"全局的", 什么是全局的? 就是, 可以在 "任何地方"使用的: ...
- 工欲善其事 之 Web 前端调试工具格式化混淆过的 JS 代码
工欲善其事 之 Web 前端调试工具格式化混淆过的 JS 代码 太阳火神的漂亮人生 (http://blog.csdn.net/opengl_es) 本文遵循"署名-非商业用途-保持一致&q ...
- jeecg中ajax传值的前端js和后台代码
前端js: var b=1; $.ajax({ type : "POST", --Post请求方式 url : 'orderController.do?wuliao', --路径 ...
随机推荐
- 最大子矩阵和(二维矩阵转一维DP)
题目描述 蒜头君拿到了一个矩阵,他想知道其中的最大非空子矩阵和是多少. 输入格式 第一行输入两个整数 n,m代表这个矩阵的行数和列数.接下来n行,每行m个整数 ai1,ai2,ai3⋯aim.(1≤m ...
- Mac系统下查看Android studio默认debug签名与正式签名的SHA1值
https://blog.csdn.net/weixin_32364917/article/details/80095063 获取默认debug签名SHA1值方法,也可以直接打开系统的终端 输入: k ...
- PAT Advanced 1038 Recover the Smallest Number (30) [贪⼼算法]
题目 Given a collection of number segments, you are supposed to recover the smallest number from them. ...
- saturates|meteoric|enclose|marooned|predators|Pioneer community|salinization|condenser|embodied
saturates渗透 meteoric蒸汽 enclose包围 Pioneer community 先锋群落 Climax community顶级群落 cumulative积累 Rebound 回弹 ...
- js实现新闻滚动-单行滚动或者多行滚动
注明:都是转载. 先说单行滚动: --------直接复制以下代码即可试验 转载http://www.3lian.com/edu/2011/06-30/4986.html----------- < ...
- Using sudo inside a docker container
https://stackoverflow.com/questions/25845538/using-sudo-inside-a-docker-container FROM ubuntu:12.04 ...
- Linux设置环境变量PATH路径的两种方法
echo 'export dataPath=$HOME/data/pre' >> ~/.bash_profile 路径即刻生效: . .bash_profile 或 source .bas ...
- angular 父子组件传值 用get set 访问器设置默认值
private _PLACEHOLDER: string; @Input() public set placeholder(v: string) { this._PLACEHOLDER = v; } ...
- java.lang.SecurityException: java.lang.IllegalStateException: java.io.FileNotFoundException:XXXXXX(系统找不到指定文件)
项目启动成功过,但访问页面抛出异常. 在Maven项目启动的时候,tomcat缓存机制没有吧maven jar除外的jar执行到项目里面,所有不要慌,项目重新启动就OK了, 如果这样还是不行的话就找到 ...
- 黑马eesy_15 Vue:03.生命周期与ajax异步请求
黑马eesy_15 Vue:02.常用语法 黑马eesy_15 Vue:03.生命周期 黑马eesy_15 Vue:04.Vue案例(ssm环境搭建) vue的生命周期与ajax异步请求 1.Vue的 ...