码迷,mamicode.com
首页 > 其他好文 > 详细

常用函数封装

时间:2019-09-01 18:51:39      阅读:105      评论:0      收藏:0      [点我收藏+]

标签:属性   attr   on()   日期格式化   日期格式   get   eth   nts   seconds   

1.日期格式化功能

function createDate(){
var d = new Date();
var y = d.getFullYear();
var m = d.getMonth();
var mydate = d.getDate();
var myday = d.getDay();
var h = d.getHours();
var mts = d.getMinutes();
var s = d.getSeconds();

switch(myday){
case 0:myday = "星期日";break;
case 1:myday = "星期一";break;
case 2:myday = "星期二";break;
case 3:myday = "星期三";break;
case 4:myday = "星期四";break;
case 5:myday = "星期五";break;
case 6:myday = "星期六";break;
}
return {
year:y,
month:createZero(m+1),
date:createZero(mydate),
day:myday,
hours:createZero(h),
minutes:createZero(mts),
seconds:createZero(s)
};
}
2.数值的补零(小于10补零)

function createZero(n){
return n<10 ? "0"+n : n;
}
3.计算两个日期之间的差值
function dateDiff(d1,d2){
var oldDate = new Date(d1);
var newDate = d2 ? new Date(d2) : new Date();

var t = Math.abs(oldDate.getTime() - newDate.getTime());

var d = parseInt(t/1000/60/60/24);
var h = parseInt((t - d*24*60*60*1000)/1000/60/60);
var m = parseInt((t - d*24*60*60*1000 - h*60*60*1000)/1000/60);
var s = parseInt((t - d*24*60*60*1000 - h*60*60*1000 - m*60*1000)/1000);

return {
day:d,
hours:h,
minutes:m,
seconds:s
}
}
4.获取范围随机数
function random(max,min){
return Math.round(Math.random()*(max-min)+min);
5.获取随机颜色
function random(max,min){
return Math.round(Math.random()*(max-min)+min);
function randomColor(){
return "rgb("+random(0,255)+","+random(0,255)+","+random(0,255)+")";
6.获取非行内样式
function getStyle(ele,attr){
if(ele.currentStyle){
return ele.currentStyle[attr];
}else{
return getComputedStyle(ele,false)[attr];
}
}
7.阻止冒泡事件
function stopBubble(e){
if(e.stopPropagation){
e.stopPropagation();
}else{
e.cancelBubble = true;
}
}
8.阻止默认事件
function stopDefault(e){
if(e.preventDefault){
e.preventDefault()
}else{
e.returnValue = false;
}
}
9.不同元素,不同属性的缓冲
function move(ele,obj){
clearInterval(t);
t = setInterval(() => {
for(var i in obj){
var iNow = parseInt(getStyle(ele,i));
var speed = (obj[i] - iNow)/7;
speed = speed<0 ? Math.floor(speed) : Math.ceil(speed);
if(obj[i] == iNow){
clearInterval(t);
}else{
ele.style[i] = iNow + speed + "px";
}
}
}, 30);
}





function getStyle(ele,attr){
if(ele.currentStyle){
return ele.currentStyle[attr];
}else{
return getComputedStyle(ele,false)[attr];
}
}






常用函数封装

标签:属性   attr   on()   日期格式化   日期格式   get   eth   nts   seconds   

原文地址:https://www.cnblogs.com/cxyuan/p/11443039.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!