JS库


//毫秒转换成时间格式方法
function timestampToTime(timestamp) { var date = new Date(timestamp);//时间戳为10位需*1000,时间戳为13位的话不需乘1000 Y = date.getFullYear() + '-'; M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-'; D = date.getDate() + ' '; h = date.getHours() + ':'; m = date.getMinutes() + ':'; s = date.getSeconds(); return Y+M+D+h+m+s; }

 

new Date().Format("yyyy年MM月dd日"); //时间格式的转换

Date.prototype.Format = function (fmt) {
  var o = {
    "M+": this.getMonth() + 1, //月份
    "d+": this.getDate(), //日
    "h+": this.getHours(), //小时
    "m+": this.getMinutes(), //分
    "s+": this.getSeconds(), //秒
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度
    "S": this.getMilliseconds() //毫秒
  };
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;
}

 

var wm_txt1 = $("#salesNoId").val().trim(); //水印显示的内容    给表格添加水印

var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'rgba(0,0,0,0.1)';
ctx.clearRect(0, 0, 100, 100);
ctx.font = '20px Arial';
ctx.translate(30, 100);
ctx.rotate(-45 * Math.PI / 180);
ctx.fillText(wm_txt1, 0, 18);
var imgdata = canvas.toDataURL();
var tbccChild = document.getElementById("index_table"); //表格的id
tbccChild.style.backgroundImage = 'url(' + imgdata + ')';

 

//获取当前时间的前一天,后一天
let curDate = new Date(); 
let preDate = new Date(curDate.getTime() - 24*60*60*1000); 

 

//图片懒加载
<img src="" class="image-item" lazyload="true"  data-original="images/1.png"/>
<!--原理:首先将页面上的图片的 src 属性设为空字符串,而图片的真实路径则设置在data-original属性中,
当页面滚动的时候需要去监听scroll事件,在scroll事件的回调中,判断我们的懒加载的图片是否进入可视区域,
如果图片在可视区内将图片的 src 属性设置为data-original 的值,这样就可以实现延迟加载-->

let viewHeight =document.documentElement.clientHeight//获取可视区高度
function lazyload(){
    let eles=document.querySelectorAll('img[data-original][lazyload]') //获取所有的图片
    Array.prototype.forEach.call(eles,function(item,index){
        let rect
        if(item.dataset.original===""){
            return
        }
        rect=item.getBoundingClientRect()// 用于获得页面中某个元素的左,上,右和下分别相对浏览器视窗的位置
        if((rect.bottom >=0) && (rect.top < viewHeight)){
            !function(){
                var img=new Image()
                img.src=item.dataset.url
                img.onload=function(){
                    item.src=img.src
                }
                item.removeAttribute("data-original")//移除属性,下次不再遍历
                item.removeAttribute("lazyload")
            }()        
        }
     })
}
lazyload()//刚开始还没滚动屏幕时,要先触发一次函数,初始化首页的页面图片
document.addEventListener("scroll",lazyload)

 

//单行写一个评级组件
let rate=2;
"★★★★★☆☆☆☆☆".slice(5 - rate, 10 - rate);
//给所有标签加边框
[].forEach.call($$("*"),function(a){
    a.style.outline="1px solid #"+(~~(Math.random()*(1<<24))).toString(16)
})

 

//数值取整
~~2.33
2.33 | 0
2.33 >> 0

 

// 构造函数,变量为15位或者18位的身份证号码
function clsIDCard(CardNo) {
    this.Valid=false;
    this.ID15='';
    this.ID18='';
    this.Local='';
    if(CardNo!=null)this.SetCardNo(CardNo);
}

// 设置身份证号码,15位或者18位
clsIDCard.prototype.SetCardNo = function(CardNo) {
    this.ID15='';
    this.ID18='';
    this.Local='';
    CardNo=CardNo.replace(" ","");
    let strCardNo;
    if(CardNo.length==18) {
      pattern= /^\d{17}(\d|x|X)$/;
      if (pattern.exec(CardNo)==null)return;
      strCardNo=CardNo.toUpperCase();
    } else {
      pattern= /^\d{15}$/;
      if (pattern.exec(CardNo)==null)return;
      strCardNo=CardNo.substr(0,6)+'19'+CardNo.substr(6,9)
      strCardNo+=this.GetVCode(strCardNo);
    }
    this.Valid=this.CheckValid(strCardNo);
}

// 校验身份证有效性
clsIDCard.prototype.IsValid = function() {
    return this.Valid;
}

// 返回生日字符串,格式如下,1981-10-10
clsIDCard.prototype.GetBirthDate = function() {
    let BirthDate='';
    if(this.Valid)BirthDate=this.GetBirthYear()+'-'+this.GetBirthMonth()+'-'+this.GetBirthDay();
    return BirthDate;
}
  
// 返回生日中的年,格式如下,1981
clsIDCard.prototype.GetBirthYear = function() {
    let BirthYear='';
    if(this.Valid)BirthYear=this.ID18.substr(6,4);
    return BirthYear;
}
  
// 返回生日中的月,格式如下,10
clsIDCard.prototype.GetBirthMonth = function() {
    let BirthMonth='';
    if(this.Valid)BirthMonth=this.ID18.substr(10,2);
    if(BirthMonth.charAt(0)=='0')BirthMonth=BirthMonth.charAt(1);
    return BirthMonth;
}
  
// 返回生日中的日,格式如下,10
clsIDCard.prototype.GetBirthDay = function() {
    let BirthDay='';
    if(this.Valid)BirthDay=this.ID18.substr(12,2);
    return BirthDay;
}

// 返回性别,1:男,0:女
clsIDCard.prototype.GetSex = function() {
    let Sex='';
    if(this.Valid)Sex=this.ID18.charAt(16)%2;
    return Sex;
}
  
// 返回15位身份证号码
clsIDCard.prototype.Get15 = function() {
    let ID15='';
    if(this.Valid)ID15=this.ID15;
    return ID15;
}
  
// 返回18位身份证号码
clsIDCard.prototype.Get18 = function() {
    let ID18='';
    if(this.Valid)ID18=this.ID18;
    return ID18;
}

// 返回所在省,例如:上海市、浙江省
clsIDCard.prototype.GetLocal = function() {
    let Local='';
    if(this.Valid)Local=this.Local;
    return Local;
}

clsIDCard.prototype.GetVCode = function(CardNo17) {
    let Wi = new Array(7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2,1);
    let Ai = new Array('1','0','X','9','8','7','6','5','4','3','2');
    let cardNoSum = 0;
    for (let i=0; i<CardNo17.length; i++)cardNoSum+=CardNo17.charAt(i)*Wi[i];
    var seq = cardNoSum%11;
    return Ai[seq];
}
  
clsIDCard.prototype.CheckValid = function(CardNo18) {
    if(this.GetVCode(CardNo18.substr(0,17))!=CardNo18.charAt(17))return false;
    if(!this.IsDate(CardNo18.substr(6,8)))return false;
    var aCity={11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",21:"辽宁",22:"吉林",23:"黑龙江 ",31:"上海",32:"江苏",33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",42:"湖北 ",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆",51:"四川",52:"贵州",53:"云南",54:"西藏 ",61:"陕西",62:"甘肃",63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外"};
    if(aCity[parseInt(CardNo18.substr(0,2))]==null)return false;
    this.ID18=CardNo18;
    this.ID15=CardNo18.substr(0,6)+CardNo18.substr(8,9);
    this.Local=aCity[parseInt(CardNo18.substr(0,2))];
    return true;
}
  
clsIDCard.prototype.IsDate = function(strDate) {
    let r = strDate.match(/^(\d{1,4})(\d{1,2})(\d{1,2})$/);
    if(r==null)return false;
    var d= new Date(r[1], r[2]-1, r[3]);
    return (d.getFullYear()==r[1]&&(d.getMonth()+1)==r[2]&&d.getDate()==r[3]);
}

let checkFlag = new clsIDCard(idCard);
console.log(checkFlag.IsValid())

 

//防止按钮多次点击 元素和间隔时间
var delayBtnClick=function($btn,time){
    var forbidFn=function(e){
        e.preventDefault();
        e.stopPropagation();
        return false;
    };
    $btn.attr("disabled","disabled");
    $btn.on("touchstart",forbidFn);
    setTimeout(function(){
        $btn.removeAttr("disabled");
        $btn.off("touchstart",forbidFn);
    },time||4000);
};

 

使用jQuery动画,让滚动条滚动到相应的位置
滚动到顶部
$('.scroll_top').click(function(){$('html,body').animate({scrollTop: '0px'}, 800);});

滚动到指定位置
$('.scroll_a').click(function(){$('html,body').animate({scrollTop:$('.a').offset().top}, 800);});

滚到到底部
.bottom的元素就是最底下的
 $('.scroll_bottom').click(function(){$('html,body').animate({scrollTop:$('.bottom').offset().top}, 800);});

 

//实现通知滚动代码
/*
* 参数说明
* obj : 动画的节点,包裹滚动内容的父元素
* top : 动画的高度,本例中是-35px;注意向上滚动是负数
* time : 动画的速度,即完成动画所用时间,本例中是500毫秒,即marginTop从0到-35px耗时500毫秒
* function : 回调函数,每次动画完成,marginTop归零,并把此时第一条信息添加到列表最后;
*/
function noticeUp(obj,top,time) {
     $(obj).animate({
         marginTop: top
         }, time, function () {
         $(this).css({marginTop:"0"}).find(":first").appendTo(this);
     })
}
调用形式:setInterval("noticeUp('.notice ul','-35px',500)", 2000);

html:
<div class="notice">
      <ul>
        <li>第1条公告第1条公告第1条公告第1条公告第1条公告第1条公告</li>
        <li>第2条公告第2条公告第2条公告第2条公告第2条公告第2条公告</li>
        <li>第3条公告第3条公告第3条公告第3条公告第3条公告第3条公告</li>
        <li>第4条公告第4条公告第4条公告第4条公告第4条公告第4条公告</li>
    </ul>
</div>

css:
div,ul,li{margin: 0;padding: 0}/*先初始化一下默认样式*/
.notice {
 width: 300px;/*单行显示,超出隐藏*/
 height: 35px;/*固定公告栏显示区域的高度*/
 padding: 0 30px;
 background-color: #b3effe;
 overflow: hidden;
}
.notice ul li {
 list-style: none;
 line-height: 35px;
 /*以下为了单行显示,超出隐藏*/
 display: block;
 white-space: nowrap;
 text-overflow: ellipsis;
 overflow: hidden;
}

 

//UI说滚动时候图片隐藏,滚动停止时刻图片显示
var scroll=function(fn){
    var win=$(window);
    var callback=fn;

    var timeId;
    var isScroll=false;

    
    win.on("scroll",function(){
        if(!isScroll){
            callback("start");
        }
        callback("scroll");

        isScroll=true;

        timeId&&clearTimeout(timeId);
        timeId=setTimeout(function(){
            isScroll=false;
            callback("end");
        },200);
    });
};
scroll(function(state){
    //state:start 滚动开始 scroll 滚动中 end滚动结束
    console.log(state);
});

 

function resizeRoot(){
 var deviceWidth = document.documentElement.clientWidth,
     num = 750,
     num1 = num / 100;
 if(deviceWidth > num){
     deviceWidth = num;  
 }
 document.documentElement.style.fontSize = deviceWidth / num1 + "px";
}
//根节点HTML的字体大小初始化
resizeRoot();

window.onresize = function(){
 resizeRoot();
};

 

滚动穿透解决办法
// css 部分
.modal_open {
  position: fixed;
  height: 100%;
}

// js 部分
/**
 * ModalHelper helpers resolve the modal scrolling issue on mobile devices
 */
var ModalHelper = (function(bodyClass) {
    var scrollTop;
    return {
        afterOpen: function() {
            scrollTop = document.scrollingElement.scrollTop  ||
                        document.documentElement.scrollTop || 
                        document.body.scrollTop;
            document.body.classList.add(bodyClass);
            document.body.style.top = -scrollTop + 'px';
        },
        beforeClose: function() {
            document.body.classList.remove(bodyClass);
            document.scrollingElement.scrollTop = document.documentElement.scrollTop = document.body.scrollTop = scrollTop;
        }
    };
})('modal_open');

// method
modalSwitch: function(){
    let self = this;
    if( self.switchFlag === 'close' ){
        ModalHelper.afterOpen();
        self.switchFlag = 'open';
    }else{
        ModalHelper.beforeClose();
        self.switchFlag = 'close';
    }
}

 

/**
 * 
 * @desc 根据name读取cookie
 * @param  {String} name 
 * @return {String}
 */
function getCookie(name) {
    var arr = document.cookie.replace(/\s/g, "").split(';');
    for (var i = 0; i < arr.length; i++) {
        var tempArr = arr[i].split('=');
        if (tempArr[0] == name) {
            return decodeURIComponent(tempArr[1]);
        }
    }
    return '';
}

/**
 * 
 * @desc  设置Cookie
 * @param {String} name 
 * @param {String} value 
 * @param {Number} days 
 */
function setCookie(name, value, days) {
    var date = new Date();
    date.setDate(date.getDate() + days);
    document.cookie = name + '=' + value + ';expires=' + date;
}

/**
 * 
 * @desc 根据name删除cookie
 * @param  {String} name 
 */
function removeCookie(name) {
    // 设置已过期,系统会立刻删除cookie
    setCookie(name, '1', -1);
}

 

限制input只能输入中文
<input onkeyup="value=value.replace(/[^\u4E00-\u9FA5]/g,'')" onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^\u4E00-\u9FA5]/g,''))" />

 

/**
     * 判断是否是iphonex
     */
    function getIsIphonex () {
        var u = navigator.userAgent;
        var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
        if (isIOS) {
            if (screen.height == 812 && screen.width == 375) {
                return true;
            }
            else {
                return false;
            }
        }
    };

 

将px转换为rem

let htmlWidth = document.documentElement.clientWidth || document.body.cilentWidth;
// 获取视窗高度
let htmlDom = document.getElementsByTagName('html')[0];
htmlDom.style.fontSize = htmlWidth / 10 + 'px';
// console.log(htmlWidth,htmlWidth / 10);
//动态修改font-size
window.addEventListener('resize',()=>{
  let htmlWidth = document.documentElement.clientWidth || document.body.cilentWidth;
  let htmlDom = document.getElementsByTagName('html')[0];
  htmlDom.style.fontSize = htmlWidth / 10 + 'px';
})

//在sass文件当中
@function px2rem($px) {
  $rem:37.5px;/* 基准值iphon6 375/10 */
  @return ($px / $rem) +rem;
}
/* 以iPhone6 为主 设计给的尺寸要比实际大两倍 */
html{
  background: #f8f8f8;
}
.header{
  width: 100%;
  height: px2rem(40px);
  background: red;
  .header-content{
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: px2rem(40px);
    padding: 0 px2rem(23px);
    .header-item{
      color:#ffcdce;
      font-size: px2rem(16px);
      &:nth-child(2){//&:等同于父元素
        color: #fff;
        font-size: px2rem(17px);
      }
    }
  }
}

 

posted @ 2019-04-28 10:29  初心不负  阅读(655)  评论(0编辑  收藏  举报