我们在工作中经常需要写很多效果或方法,但是有些效果和方法我们都已经写过无数次了,因此我们会把这些代码给封闭起来,以便以后使用,以下就是我个人在工作中整理出的一些常用代码,以后会不定期更新。
1、时间格式化
Date.prototype.Format = function(format) { //对所有时间对象加上原型操作
format ? format : format = "yyyy-MM-dd hh:mm:ss"; //不传则默认format(最后一个format可以删掉)
var o = {
//this并不在对象的内部函数,此时this指Date
"M+": this.getMonth() + 1, // month
"d+": this.getDate(), // day
"h+": this.getHours(), // hour
"m+": this.getMinutes(), // minute
"s+": this.getSeconds(), // second
"q+": Math.floor((this.getMonth() + 3) / 3), // quarter
"S": this.getMilliseconds()
// millisecond
};
//如果传入format里有y则对y用get的year进行替换
if (/(y+)/.test(format)) {
//根据传入的y数量截取get的Fullyear并替换掉所有的y,保留下中间的-:等符号
format = format.replace(RegExp.$1, (this.getFullYear() + "").slice(4 - RegExp.$1.length));//如果就接一个参数,截到底,slice和substr,substring一样
}
//遍历剩下的m,h,s等
for (var k in o) {
//匹配mdh等,如果传入的format里有,则执行下面的替换
if (new RegExp("(" + k + ")").test(format)) {
//将传入的format的yyyy,MM,mm等替换为获得到mouth,date,hours
//补了两个0,如果需要03这样的效果,根据3的长度为1,从003的第2个开始截到最后,即03;如果是33则从0033的第3个开始截取到最后,即33;
//''+o[k]将数字转换成字符串然后可以.length计算其长度
format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substring(("" + o[k]).length));
}
}
return format; //返回规定格式的date时间
};
// var date = new Date() //创建时间对象
// alert(date.Format('yyyy-MM-dd hh:mm:ss'))//字母必须大小写一致,空格-等符号无所谓,Mmd等可以根据需要不传(也就不显示了)
// 直接这样用: (new Date()).Format('yyyy-MM-dd hh:mm:ss')
2、ajax
function addUrl(url,type,obj){
var arr = [];
for(var i in obj){
arr.push(i+"="+obj[i]);
}
if(type == "post"){
return arr.join("&");
}else{
var path = url+"?"+arr.join("&");
return path;
}
}
function ajaxLogin(obj){
obj.type = obj.type || "get"; //不传递时默认为get
obj.data = obj.data || {}; //不传递时默认为空
if(window.XMLHttpRequest){
ajax = new XMLHttpRequest();
}else{
ajax = new ActiveXObject("Microsoft.XMLHTTP");
}
if(obj.type.toLowerCase() == "post"){
ajax.open("POST",obj.url,true);
ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
var data = addUrl("任意值","post",obj.data);
ajax.send(data);
}else if(obj.type.toLowerCase() == "get"){
//通过自行封装的函数,将url和data拼接成字符串路径
var path = addUrl(obj.url,"get",obj.data);
ajax.open("GET",path,true);
ajax.send();
}
ajax.onreadystatechange = function() {
if (ajax.readyState==4) {
if (ajax.status>=200&&ajax.status<300||ajax.status==304) {
if(obj.onsuccess){
obj.onsuccess(ajax.responseText);
}
} else {
if(obj.onerror){
obj.onerror(ajax.status);
}
}
}
}
}
//使用方法
// ajaxLogin({
// url:"login.php",
// type:"get",
// data:{
// user:user.value,
// pass:pass.value
// },
// onsuccess:function(data){
// alert(data);
// },
// onerror:function(data){
// alert("失败了,错误信息为:"+data);
// }
// });
3、onmousewheel
function MouseWheel(ele,fun){
//判断浏览器类型
var agent = window.navigator.userAgent;
//判断是否是火狐浏览器
if(agent.indexOf("Firefox")!=-1){
ele.addEventListener("DOMMouseScroll",wheel);
}else{
ele.onmousewheel = wheel;
}
//创建一个处理向上向下滚动的函数 事件处理程序
function wheel(ev){
var down = false;
if(ev.detail>0){
down = true;
}
if(ev.wheelDelta < 0){
down = true;
}
fun(down,ele,ev);
return false;
}
}
4、拖拽
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
*{margin: 0;padding: 0;}
div{
width: 100px;
height: 100px;
background: red;
position: absolute;
}
</style>
</head>
<body>
<div></div>
</body>
<script type="text/javascript">
var div = document.querySelector("div");
//求出div的宽高
var dw = div.offsetWidth, dh = div.offsetHeight;
var maxWidth = document.documentElement.clientWidth - dw,
maxHeight = document.documentElement.clientHeight - dh;
//当鼠标按下时开始拖拽
div.onmousedown = function(e){
//获取鼠标按下时所在的位置
var cx = e.clientX, cy = e.clientY;
//求出鼠标距离元素边框的值
var fx = cx - div.offsetLeft, fy = cy - div.offsetTop;
//鼠标按下后监听鼠标移动
document.documentElement.onmousemove = function(ev){
//分别获取鼠标当前所在的位置
var x = ev.clientX-fx,
y = ev.clientY-fy;
if (x>=maxWidth) {
x = maxWidth;
}
if (x<=0) {
x = 0;
}
if (y>=maxHeight) {
y = maxHeight;
}
if (y<=0) {
y = 0;
}
//指定元素的位置为鼠标位置
div.style.left = x + 'px';
div.style.top = y + 'px';
}
}
//鼠标抬起时,删除鼠标移动事件
document.documentElement.onmouseup = function(){
document.documentElement.onmousemove = null;
}
</script>
</html>
5、Tab切换
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
*{
margin: 0px;
padding: 0px;
}
#tabs{
list-style: none;
}
#tabs li{
float: left;
width: 120px;
height: 30px;
border: 1px solid gray;
text-align: center;
line-height: 30px;
}
#content{
clear: both;
width: 364px;
border: 1px solid gray;
height: 300px;
}
#content div{
height: 100%;
text-align: center;
line-height: 300px;
display: none;
}
.active{
background: red;
}
</style>
</head>
<body>
<div id="wrap">
<ul id="tabs">
<li>标签一</li>
<li>标签二</li>
<li>标签三</li>
</ul>
<div id="content">
<div>我是标签一的内容</div>
<div>我是标签二的内容</div>
<div>我是标签三的内容</div>
</div>
</div>
</body>
<script type="text/javascript">
var lis = document.querySelectorAll("#tabs>li");
var divs = document.querySelectorAll("#content>div");
var n = 0;
for (var i = 0; i < lis.length; i++) {
lis[i].index = i;
lis[i].onclick = function(){
var index = this.index;
lis[n].className = '';
divs[n].style.display = 'none';
// var active = document.querySelectorAll(".active")[0];
// if(active){
// var a = active.index;
// lis[a].className = '';
// divs[a].style.display = 'none';
// }
divs[index].style.display = 'block';
this.className = 'active';
n = index;
}
}
</script>
</html>
6、导航滚动
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
*{
margin: 0;padding: 0;
}
.wrap{
width: 600px;
position: relative;
margin: auto;
}
ul{
width: 600px;
height: 50px;
}
li{
width: 100px;
display: inline-block;
list-style: none;
text-align: center;
}
section{
position: absolute;
top: 30px;
width: 100px;
height: 3px;
background: red;
}
section:before{
content: "";
position: absolute;
width: 0px;
height: 0px;
margin-top: -10px;
margin-left: 47px;
border-bottom: 5px solid red;
border-left: 5px solid white;
border-right: 5px solid white;
border-top: 5px solid white;
}
</style>
</head>
<body>
<div class="wrap">
<ul>
<li>首页</li><li>项目</li><li>技术</li><li>首页</li><li>项目</li><li>首页</li>
</ul>
<section id="bot"></section>
</div>
<div class="wrap">
<ul>
<li>首页</li><li>项目</li><li>技术</li><li>首页</li><li>项目</li><li>首页</li>
</ul>
<section id="bot"></section>
</div>
<div class="wrap">
<ul>
<li>首页</li><li>项目</li><li>技术</li><li>首页</li><li>项目</li><li>首页</li>
</ul>
<section id="bot"></section>
</div>
<div class="wrap">
<ul>
<li>首页</li><li>项目</li><li>技术</li><li>首页</li><li>项目</li><li>首页</li>
</ul>
<section id="bot"></section>
</div>
<div class="wrap">
<ul>
<li>首页</li><li>项目</li><li>技术</li><li>首页</li><li>项目</li><li>首页</li>
</ul>
<section id="bot"></section>
</div>
</body>
<script src="js/tween.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
var wraps = document.getElementsByClassName("wrap"); //得到wrap数组,
for(var i=0;i<wraps.length;i++){ //wrap下循环
move(wraps[i]);
}
var timer;
function move(wrap){ //wrap[i]中,再让li循环
var ul = wrap.getElementsByTagName("ul");
var list = ul[0].children; //得到wrap[i]下的li和section
var section = wrap.getElementsByTagName("section")[0];
for (var i = 0; i < list.length; i++) { //进行li循环
list[i].index = i;
list[i].onmouseover = function(){
var index = this.index;
clearInterval(timer);
var a = index*list[0].offsetWidth;
var b = section.offsetLeft; //2.初始位置
var c = a - b; //3.改变量
var step = 30; //4.步数
var start = 0; //1.初始步数变量
var change = c/step;
timer = setInterval(function(){ //section位移引入tween.js写法
start++;
if(start>=step){
clearInterval(timer);
}
section.style.left = Tween.Back.easeOut(start,b,c,step) + 'px'; //(1.初始步数变量,2.初始位置,3.改变量,4.步数)
},30)
// timer = setInterval(function(){ //section位移原始写法
// start++;
// var l = change + section.offsetLeft;
// if (start>=step) {
// l = a;
// clearInterval(timer);
// }
// section.style.left = l + 'px';
// },20)
}
}
}
</script>
</html>
7、json数据读取
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
</body>
<script type="text/javascript">
var obj = {
name: "1",
value: "1",
sub: [{
name: "1-1",
value: "2"
}, {
name: "1-2",
value: "2",
sub: [{
name: "2-1",
value: "2",
sub: [{
name: "2-1-1",
value: "2"
}, {
name: "2-1-2",
value: "2"
}]
}, {
name: "2-2",
value: "2"
}]
}]
}
test(obj.sub);
function test(arr){
for(var i=0;i<arr.length;i++){
if(arr[i].sub && arr[i].sub.length>0){
test(arr[i].sub);
}else{
alert(arr[i].name)
}
}
}
</script>
</html>
8、瀑布流
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script type="text/javascript"/>
window.onload=function(){
waterfall('main','pin');
var dataInt={'data':[{'src':'1.jpg'},{'src':'2.jpg'},{'src':'3.jpg'},{'src':'4.jpg'}]};
window.onscroll=function(){
if(checkscrollside()){
var oParent = document.getElementById('main');// 父级对象
for(var i=0;i<dataInt.data.length;i++){
var oPin=document.createElement('div'); //添加 元素节点
oPin.className='pin'; //添加 类名 name属性
oParent.appendChild(oPin); //添加 子节点
var oBox=document.createElement('div');
oBox.className='box';
oPin.appendChild(oBox);
var oImg=document.createElement('img');
oImg.src='./images/'+dataInt.data[i].src;
oBox.appendChild(oImg);
}
waterfall('main','pin');
};
}
}
/*
parend 父级id
pin 元素id
*/
function waterfall(parent,pin){
var oParent=document.getElementById(parent);// 父级对象
var aPin=getClassObj(oParent,pin);// 获取存储块框pin的数组aPin
var iPinW=aPin[0].offsetWidth;// 一个块框pin的宽
var num=Math.floor(document.documentElement.clientWidth/iPinW);//每行中能容纳的pin个数【窗口宽度除以一个块框宽度】
oParent.style.cssText='width:'+iPinW*num+'px;ma rgin:0 auto;';//设置父级居中样式:定宽+自动水平外边距
var pinHArr=[];//用于存储 每列中的所有块框相加的高度。
for(var i=0;i<aPin.length;i++){//遍历数组aPin的每个块框元素
var pinH=aPin[i].offsetHeight;
if(i<num){
pinHArr[i]=pinH; //第一行中的num个块框pin 先添加进数组pinHArr
}else{
var minH=Math.min.apply(null,pinHArr);//数组pinHArr中的最小值minH
var minHIndex=getminHIndex(pinHArr,minH);
aPin[i].style.position='absolute';//设置绝对位移
aPin[i].style.top=minH+'px';
aPin[i].style.left=aPin[minHIndex].offsetLeft+'px';
//数组 最小高元素的高 + 添加上的aPin[i]块框高
pinHArr[minHIndex]+=aPin[i].offsetHeight;//更新添加了块框后的列高
}
}
}
/****
*通过父级和子元素的class类 获取该同类子元素的数组
*/
function getClassObj(parent,className){
var obj=parent.getElementsByTagName('*');//获取 父级的所有子集
var pinS=[];//创建一个数组 用于收集子元素
for (var i=0;i<obj.length;i++) {//遍历子元素、判断类别、压入数组
if (obj[i].className==className){
pinS.push(obj[i]);
}
};
return pinS;
}
/****
*获取 pin高度 最小值的索引index
*/
function getminHIndex(arr,minH){
for(var i in arr){
if(arr[i]==minH){
return i;
}
}
}
function checkscrollside(){
var oParent=document.getElementById('main');
var aPin=getClassObj(oParent,'pin');
var lastPinH=aPin[aPin.length-1].offsetTop+Math.floor(aPin[aPin.length-1].offsetHeight/2);//创建【触发添加块框函数waterfall()】的高度:最后一个块框的距离网页顶部+自身高的一半(实现未滚到底就开始加载)
var scrollTop=document.documentElement.scrollTop||document.body.scrollTop;//注意解决兼容性
var documentH=document.documentElement.clientHeight;//页面高度
return (lastPinH<scrollTop+documentH)?true:false;//到达指定高度后 返回true,触发waterfall()函数
}
</script>
<title></title>
<style type="text/css">
*{padding: 0;margin:0;}
#main{
position: relative;
}
.pin{
padding: 15px 0 0 15px;
float:left;
}
.box{
padding: 10px;
border:1px solid #ccc;
box-shadow: 0 0 6px #ccc;
border-radius: 5px;
}
.box img{
width:162px;
height:auto;
}
</style>
</head>
<body>
<div id="main">
<div class="pin">
<div class="box">
<img src="./images/1.jpg"/>
</div>
</div>
<div class="pin">
<div class="box">
<img src="./images/2.jpg"/>
</div>
</div>
<div class="pin">
<div class="box">
<img src="./images/3.jpg"/>
</div>
</div>
<div class="pin">
<div class="box">
<img src="./images/4.jpg"/>
</div>
</div>
<div class="pin">
<div class="box">
<img src="./images/5.jpg"/>
</div>
</div>
<div class="pin">
<div class="box">
<img src="./images/6.jpg"/>
</div>
</div>
<div class="pin">
<div class="box">
<img src="./images/7.jpg"/>
</div>
</div>
<div class="pin">
<div class="box">
<img src="./images/8.jpg"/>
</div>
</div>
<div class="pin">
<div class="box">
<img src="./images/9.jpg"/>
</div>
</div>
<div class="pin">
<div class="box">
<img src="./images/10.jpg"/>
</div>
</div>
<div class="pin">
<div class="box">
<img src="./images/11.jpg"/>
</div>
</div>
<div class="pin">
<div class="box">
<img src="./images/12.jpg"/>
</div>
</div>
<div class="pin">
<div class="box">
<img src="./images/13.jpg"/>
</div>
</div>
<div class="pin">
<div class="box">
<img src="./images/14.jpg"/>
</div>
</div>
<div class="pin">
<div class="box">
<img src="./images/15.jpg"/>
</div>
</div>
<div class="pin">
<div class="box">
<img src="./images/16.jpg"/>
</div>
</div>
<div class="pin">
<div class="box">
<img src="./images/17.jpg"/>
</div>
</div>
<div class="pin">
<div class="box">
<img src="./images/18.jpg"/>
</div>
</div>
<div class="pin">
<div class="box">
<img src="./images/19.jpg"/>
</div>
</div>
<div class="pin">
<div class="box">
<img src="./images/20.jpg"/>
</div>
</div>
<div class="pin">
<div class="box">
<img src="./images/21.jpg"/>
</div>
</div>
</div>
</body>
</html>