常用js整理

/**
 * 判断图片是否加载完毕,显示默认图片
 * @param {type} imgObj
 * @returns {undefined}
 */
function imgLoad(imgObj){  
    imgObj.each(function(i){
        if (imgObj.eq(i).attr('dataimg') == undefined) {
            return;
        }
        var val=imgObj.eq(i).attr('dataimg');
        var img=new Image(); 
        img.οnlοad=function(){ 
            if(img.complete==true){
                imgObj.eq(i).attr('src',val);
            } 
        }        
        //如果因为网络或图片的原因发生异常,则显示该图片 
        img.οnerrοr=function(){img.src='loading.gif'}
        img.src = val; 
    })
} 
//imgLoad($('#text_content img'));
/**
 * 判断图片是否加载完毕,显示默认图片
 * @param {type} imgObj
 * @returns {undefined}
 */
function lodingImg(){
    $('#topbanner img,.com_list img').each(function(){
        if($(this).offset().top<=$(document).scrollTop()+$(window).height() 
        && $(this).offset().top>=$(document).scrollTop()) {
            var url = $(this).attr('loding'),
            img = $(this).attr('src');
            if(img!=url){
                $(this).attr({src:url,alt:''}).css({opacity:0}).animate({opacity:1},500);
            }
        }
    });
}
lodingImg();//加载图片
//窗口改变大小加载
$(window).resize(function(){    
    lodingImg();//加载图片
});

//获取滚动条当前的位置 
function getScrollTop(){ 
    var scrollTop = 0; 
    if (document.documentElement && document.documentElement.scrollTop){ 
        scrollTop = document.documentElement.scrollTop; 
    }else if (document.body) { 
        scrollTop = document.body.scrollTop; 
    } 
    return scrollTop; 
} 

//获取当前可是范围的高度 
function getClientHeight(){ 
    var clientHeight = 0; 
    if (document.body.clientHeight && document.documentElement.clientHeight){ 
        clientHeight = Math.min(document.body.clientHeight, document.documentElement.clientHeight); 
    } else { 
        clientHeight = Math.max(document.body.clientHeight, document.documentElement.clientHeight); 
    } 
    return clientHeight; 
} 

//获取文档完整的高度 
function getScrollHeight(){ 
    return Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); 
}
/**
 * 滚动加载
 */
$(window).scroll(function(){
    if (getScrollTop() + getClientHeight() >= getScrollHeight()){ 
         nextPage();
     } 
     lodingImg();
  });  

//返回顶部
$(window).scroll(function() {
    var scrollTop = $(document).scrollTop();
    if (scrollTop >= 300) {
        $('#up').css({'display':'block'})

    } else {
        $('#up').css({'display':'none'})
    }

});
$('#up').click(function() {
    $('html,body').animate({
        scrollTop: '0px'
    }, 500);
});

/**
 * 选项卡代码展示
 */
$(".nav-tab li").click(function() {
    var d=$(".nav-tab li").index(this)
    $(".visa-details .visa-detail").hide();
    $(".visa-details .visa-detail").eq(d).show();
    $(".nav-tab li").removeClass('current');
    $(this).addClass('current');
});

/**
 * 注册验证函数
 */
function reg() {
    //验证姓名
    var user = /^.*[\u4e00-\u9fa5]+.*$/;
    if ($(".user").val() == "" || $(".user").val() == "为方便核实信息请填写真实姓名") {
        myalert("请填写真实姓名");
        return false;
    } else if (!user.test($(".user").val())) {
        myalert("请输入中文姓名");
        return false;
    }
    //验证手机
    var phone = /^1[3|4|5|8][0-9]\d{4,8}$/i;
    if ($(".phone_input").val() == "" || $(".phone_input").val() == "请输入中国大陆手机号") {
        myalert("请输入正确的手机号");
        return false;
    } else if (!phone.test($(".phone_input").val()) || $(".phone_input").val().length < 11) {
        myalert("请输入正确的手机号");
        return false;
    }
    //验证邮箱
    var email = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/ 
    if ($(".email").val() == "" || !email.test($(".email").val())) {
        myalert("请输入正确的邮箱");
        return false;
    }
    //阅读条款
    if (!$('#Icheck').is(':checked')) {
        myalert("请认真阅读并同意以下条款");
        return false;
    }
    return true;
}

/**
 * 点击返回上一页面
 */
$('.left_back').click(function(event) {
    if(jQuery(this).attr("href")){
        window.location.href = jQuery(this).attr("href");
        return;
    }
    var refer=document.referrer;
    if(!refer || refer ==window.location.href){
        window.location.href = '/';
    }else{
        window.history.back();
    }
});

/**
 * 去除图片的style,width,height样式
 * 使得图片自适应M端页面
 */
function rmImgStyle() {
    var imgs = document.getElementById('text_content').getElementsByTagName('img');
    for(var i = 0 ; i < imgs.length ; i++){
        imgs[i].removeAttribute("width");
        imgs[i].removeAttribute("height");
        imgs[i].removeAttribute('style');
        imgs[i].setAttribute("width", "100%");
    }  
}

/**
 * 异步加载
 */
var currentPage =1;
var pages = 8; //pages = {:$pageNum:}
function nextPage(){
    if (pages == 0){
        return;
    }
    currentPage++;
    if(currentPage>pages){
        jQuery('#no_more').show();
        return;
    }
    if(currentPage>1){
         jQuery('.loading').show();
    }
    var response = $.ajax({
        type: "POST",
        url: "/index.php?m=default&c=index&a=ghomeAjax",
        data: {
            "page" : currentPage,
        },
        success: function(data){
            jQuery('.com_list ul').append(data);
            jQuery('.loading').hide();
        },
         async: true
     });
 }
//滚动不断进行加载
$(window).scroll(function(){
    if (getScrollTop() + getClientHeight() >= getScrollHeight()){ 
         nextPage();
     } 
     lodingImg();
});

/**
 * js验证手机
 */
function checkPhone(phone){    
    if(!(/^1[3|4|5|7|8]\d{9}$/.test(phone))){
        return false; 
    } 
    return true;
}
/**
 * js验证邮箱
 */
function checkEmail(str){
    var re = /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/
    if(re.test(str)){
        return true;
    }else{
        return false;
    }
}
/**
 * js验证QQ
 */
function isQQ(pQQ){  
    var bValidate = RegExp(/^[1-9][0-9]{4,9}$/).test(pQQ);  
    if (bValidate){  
        return true;  
    }else{ 
        return false;  
    }
}  
/**
 * 判断是否为微信
 */
function isWeiXin(){
    var ua = window.navigator.userAgent.toLowerCase();
    if(ua.match(/MicroMessenger/i) == 'micromessenger'){
        return true;
    }else{
        return false;
    }
}

/**
 * 判断网站是否加载完成
 * @type subSomething 加载状态改变的时候执行这个方法
 */
document.onreadystatechange = subSomething; 
function subSomething(){
    //当页面加载状态
    if(document.readyState == "complete") { 
        console.log("加载完成");
        console.log(document.readyState);
    }
}

/**
 * 获取页面加载完成所需时间
 * @returns loadTime 所需时间
 */
window.onload = function () {
    var loadTime = window.performance.timing.domContentLoadedEventEnd-window.performance.timing.navigationStart; 
    console.log('Page load time is '+ loadTime);
}

/**
 * 获取页面访问所在地
 * 引用新浪的js
 * http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js
 * @type remote_ip_info
 */
var mycity = remote_ip_info;
if(remote_ip_info['province']==remote_ip_info['city']){
    console.log("您好,欢迎来自 "+remote_ip_info['city']+" 的网友");
}else{
    console.log("您好,欢迎来自 "+remote_ip_info['province']+' '+remote_ip_info['city']+" 的网友");
}

/**
 * 判断两个时间的大小
 * @param {type} stime 开始时间
 * @param {type} etime 结束时间
 * @returns {Boolean}
 */
function contrastTime(stime,etime){
    stime = stime.replace(/-/g,'/'); 
    stime = stime.replace('T',' '); 
    var date =  new Date(stime); 
    stime = date.getTime().toString();
    stime = stime.substr(0, 10);

    etime = etime.replace(/-/g,'/'); 
    etime = etime.replace('T',' '); 
    date =  new Date(etime); 
    etime = date.getTime().toString();
    etime = etime.substr(0, 10);
    return etime>=stime ? true : false;
}

/**
 * 获取当前日期时间
 * @returns {String}
 */
function nowDate(){
    var myDate = new Date();
    return myDate.getFullYear()+'-'+doubleDigit(myDate.getMonth()+1)+'-'+doubleDigit(myDate.getDate())+' '+doubleDigit(myDate.getHours())+':'+doubleDigit(myDate.getMinutes());
}
/**
 * 月份,天数,时间位数补零操作
 * @param {type} num
 * @returns {String}
 */
function doubleDigit(num){
    return num<10 ? '0'+num : num;
}

/**
 *@param 获取当前时间戳
 */
function get_time_stamp(){
    var timestamp = new Date().getTime();
    //timestamp = timestamp/1000;
    return timestamp;
}

/**
 * 指定日期时间转为时间戳格式
 * @param {type} dateStr
 * @returns {String}
 */
function get_unix_time(dateStr){
    var date =  new Date(dateStr); 
    var time_str = date.getTime().toString();
    //return time_str.substr(0, 10);
    return time_str;
}

/**
 * 二维码生成
 * 需要引入 jquery.qrcode.min.js
 */
function weixin(){ 
    $('.wxBox').css("display","block");
    //二维码后面的黑色弹层
    $('.bg').css("display","block");
    //放置二维码的容器
    $('#qrcodeDiv').qrcode({
        "width":180,
        "height":180,
        "correctLevel":0,
        "text":window.location.href
    });
    jQuery('.float-share').hide();
    var canvas = $('#qrcodeDiv canvas');
    //生成二维码图片
    var img = canvas.get(0).toDataURL("image/png");
    var pHtml = '<img src="'+img+'" width="180" height="180"/>';
    //把二维码图片放入容器中
    $('#qrcodeDiv').html(pHtml);
}

/**
 * 生成带有logo的二维码
 * @param {type} img 即是logo的地址
 */
function logoQrcode(img){
	jQuery('#output').qrcode({
	  text: window.location.href, //text: "www.58haha.cn"
	  height: 250,
	  width: 250,
	  correctLevel: 0,
	  src: img //这里配置Logo的地址即可。
	});
}

/**
 * QQ,Sina,人人分享接口
 * @param {type} type 分享的类型
 * @param {type} url 分享的url
 * @param {type} title 分享的标题
 * @param {type} img 分享的图片
 * @param {type} content 分享的描述
 */
function shareys(type, url, title, img, content){  
    switch (type) {
        case "sina":
            url = "http://service.weibo.com/share/share.php?title=" + encodeURIComponent(content + '「' + title + '」' + ' 点这里' + url) + '&pic=' + img;
            window.open(url);
            break;
        case "tqq":
            url = "http://share.v.t.qq.com/index.php?c=share&a=index&url=" + encodeURIComponent(url) + '&title=' + encodeURIComponent(title) + '&pic=' + img;
            window.open(url);
            break;
        case "qzone":
             url = 'http://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?url=' + encodeURIComponent(url) + '&title=' + encodeURIComponent(title) + '&site=&pics=' + encodeURIComponent(img) + '&desc=' + encodeURIComponent(content) +'&summary=' + encodeURIComponent(content);
            window.open(url);
            break;
        case "ren":
            url = 'http://widget.renren.com/dialog/share?resourceUrl=' + encodeURIComponent(url) + '&srcUrl=' + img + '&title=' + encodeURIComponent(title);
            +'&description=' + content;
            window.open(url);
            break;
        default:
            break;
    }
}

/**
 * 页面html代码转为图片
 * 需要引入 html2canvas
 */
function html2Img(){
    img.src='/qrcode.jpg';
    var img = new Image();
    img.onload = function(){
        var elem = jQuery('#content');
        html2canvas([elem.get(0)], {
            onrendered: function (canvas) {
                var image = canvas.toDataURL("image/jpg");
                var pHtml = "<img src='"+image+"' style='width:100%;height:100%'>";
                jQuery("#content").html(pHtml);
                jQuery("#content").attr("style","padding-top:40px");
                jQuery("#content").attr("style","padding-bottom:40px");
            }
        }); 
    }
}
/**
 * 校验身份证号码
 * @param {type} code 身份证号
 * @returns {Boolean}
 */
function IdentityCodeValid(code) { 
    var city={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:"国外 "};
    var tip = "";
    var pass= true;
    
    if(!code || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[12])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(code)){
        tip = "身份证号格式错误";
        pass = false;
    }
    else if(!city[code.substr(0,2)]){
        tip = "地址编码错误";
        pass = false;
    }
    else{
        //18位身份证需要验证最后一位校验位
        if(code.length == 18){
            code = code.split('');
            //∑(ai×Wi)(mod 11)
            //加权因子
            var factor = [ 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 ];
            //校验位
            var parity = [ 1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2 ];
            var sum = 0;
            var ai = 0;
            var wi = 0;
            for (var i = 0; i < 17; i++)
            {
                ai = code[i];
                wi = factor[i];
                sum += ai * wi;
            }
            var last = parity[sum % 11];
            if(parity[sum % 11] != code[17]){
                tip = "校验位错误";
                pass =false;
            }
        }
    }
    if(!pass) alert(tip);
    return pass;
}

/**
 * 页面访问设备识别
 */
function pcOrPhone(){
    if(/AppleWebKit.*Mobile/i.test(navigator.userAgent) || (/MIDP|SymbianOS|NOKIA|SAMSUNG|LG|NEC|TCL|Alcatel|BIRD|DBTEL|Dopod|PHILIPS|HAIER|LENOVO|MOT-|Nokia|SonyEricsson|SIE-|Amoi|ZTE/.test(navigator.userAgent))){
        try{
            if(/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)){
                //触屏手机版地址
                window.location.href="http://m.39yst.com/";
            }else if(/iPad/i.test(navigator.userAgent)){
                //pad版地址
                window.location.href="http://pad.39yst.com/";
            }else{
                //普通手机版地址
                window.location.href="http://m.39yst.com/";
            }
        }
        catch(e){}
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值