zoukankan      html  css  js  c++  java
  • 备注:常用Js脚本

    一、Cookies操作:

    代码
    function clearCookie() {
    var now =new Date();
    var yesterday =new Date(now.getTime() -1000*60*60*24);
    this.setCookie('co'+this.obj, 'cookieValue', yesterday);
    this.setCookie('cs'+this.obj, 'cookieValue', yesterday);
    this.setCookie('keep', 'cookieValue', yesterday);
    };

    function setCookie(cookieName, cookieValue, expires, path, domain, secure) {
    document.cookie
    =
    escape(cookieName)
    +'='+ escape(cookieValue)
    + (expires ?'; expires='+ expires.toGMTString() : '')
    + (path ?'; path='+ path : '')
    + (domain ?'; domain='+ domain : '')
    + (secure ?'; secure' : '');
    };

    function getCookie(cookieName) {
    var cookieValue ='';
    var posName = document.cookie.indexOf(escape(cookieName) +'=');
    if (posName !=-1) {
    var posValue = posName + (escape(cookieName) +'=').length;
    var endPos = document.cookie.indexOf(';', posValue);
    if (endPos !=-1) cookieValue = unescape(document.cookie.substring(posValue, endPos));
    else cookieValue = unescape(document.cookie.substring(posValue));
    }
    return (cookieValue);
    };

    二、浏览器多语言切换:

    代码
    function ChangeLang() {
    if(document.documentElement.lang =='en-us') {
    javascript:OnLangSelectionChange(
    2052);
    }
    else {
    javascript:OnLangSelectionChange(
    1033);
    }
    }

    function OnLangSelectionChange(value)
    {
    var today =new Date();
    var oneYear =new Date(today.getTime() +365*24*60*60*1000);
    var url = window.location.href;
    document.cookie
    ='lcid='+ value +';path=/;expires='+ oneYear.toGMTString();
    window.location.href
    = url;
    }

    三、正则表达式颜色值,空值:

    代码
    function checkColor(str) {
    var pattern =/^#[0-9a-fA-F]{6}$/;
    if (str.match(pattern) ==null)
    returnnull;
    else
    returnstr;
    }
     
    function replaceSpace(str) {
      
    if (str ==null)
           
    returnnull;
      
    else         
           
    return str.replace(/\s/g, '');
    }

    四、判断是否是数值,验证Email,判断手机号

    代码
    function IsNumber(fData)
    {
    var reg =new RegExp("^[-]?[0-9]+[\.]?[0-9]+$");
    return reg.test(fData)
    }

    function IsEmail(fData)
    {
    var reg =new RegExp("^[0-9a-zA-Z]+@[0-9a-zA-Z]+[\.]{1}[0-9a-zA-Z]+[\.]?[0-9a-zA-Z]+$");
    return reg.test(fData);
    }

    function IsPhone(fData)
    {
    var reg =/^(\+86)?(1[0-9]{10})$/;
    return reg.test(fData);
    }

     五、获取兼容浏览器鼠标位置:

    代码
    var mousePos;
    function mouseMove(ev) {
    ev
    = ev || window.event;
    mousePos
    = mouseCoords(ev);
    }
    function mouseCoords(ev) {
    if (ev.pageX || ev.pageY) {
    return { x: ev.pageX, y: ev.pageY };
    }
    return {
    x: ev.clientX
    + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft),
    y: ev.clientY
    + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop)
    };
    }
    document.onmousemove
    = mouseMove;

     六、获取html元素坐标:

    代码
    var getPos:function(o){//取元素坐标
    var x =0, y =0;
    do{
    x
    += o.offsetLeft;
    y
    += o.offsetTop;
    }
    while(o=o.offsetParent);
    return {'x':x,'y':y};
    }
    var pos=getPos(obj);
    alert(pos.x);

    七、关闭弹出页面,无提示对话框:

    代码
    var winClose:function(){//取元素坐标
        window.opener=null;
        window.open("",'_self',"");
        window.close();
    }

    八、Onload事件注册

    代码
    function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload !='function') {
    window.onload
    = func;
    }
    else {
    window.onload
    =function() {
    if (oldonload) {
    oldonload();
    }
    func();
    }
    }
    }

    九、计算两个时间差

    代码
    function DateDiff(sdt,edt)
    {
     var s=new Date(sdt);
     var e=new Date(edt);//Days
     var df=(endDate.getTime()-startDate.getTime())/3600/1000/24;
     return dt;
    }

    十、四舍五入

    代码
    function ForDight(Dight,How)
    {
      var c=Math.pow(10,How);
      return Math.round(Dight*c)/c;
    }
     

     十一、自动滚到页面底部

    <body onload="scrollTo(0,document.body.scrollHeight)">

     十二、去除其他符号,得到数字

    代码
    function FilterNum(str) {
        return str.replace(/\D+/, '');
    }

     十三、获取Request Url 参数

    代码
    function getQry(key){
      var search=location.search.slice(1);//得到get方式提交的查询字符串
      var arr=search.split("&");
      for(var i=0;i<arr.length;i++){
       var ar=arr[i].split("=");
       if(ar[0]==key){
           return ar[1];
          }
      }
    }

     十四、弹出对话框页面

    View Code
    function OpenNewWindow(pageUrl) {
    var lanTitle = 'Add a new task.';
    var options = {
    url: pageUrl,
    title: lanTitle,
    allowMaximize: false,
    showClose: true,
    dialogReturnValueCallback: demoCallback
    };
    function demoCallback() {
    SP.UI.ModalDialog.RefreshPage(SP.UI.DialogResult.OK);
    }
    SP.UI.ModalDialog.showModalDialog(options);
    }

     十五、获取URL参数值

    View Code
    var str = location.search.match(/xmbh=[^&]+/)[1];
    var id = location.search.match(/ID=(\d+)/)[1];

     十六、关闭页面时提示

        //添加提示
        $(window).bind('beforeunload', function () { return 'Are you sure to leave this page?  The unsaved data will be lost!'; });
        //提交时解除提示
        $(window).unbind('beforeunload');
    View Code

     十七、随机生成颜色值

    color: function (value){ return "#"+("00000"+((Math.random()*16777215+0.5)>>0).toString(16)).slice(-6); }
    View Code

     十八、Echarts 函数

    function ShowBaiduBar(divBar, xLabel, yData, titleStr)
    {
        option = {
            title: {
                text: titleStr
            },
            tooltip: {
                trigger: 'axis'
            },
            legend: {
                data: ['实施率(%)']
            },
            toolbox: {
                show: true,
                feature: {
                    mark: { show: true },
                    dataView: { show: true, readOnly: false },
                    magicType: { show: true, type: ['line', 'bar'] },
                    restore: { show: true },
                    saveAsImage: { show: true }
                }
            },
            calculable: true,
            xAxis: [
                {
                    type: 'category',
                    data:xLabel,
                    axisLabel: {
                        show: true,
                        rotate: 60,
                        textStyle: {
                            color: '#920022'
                        }
                    }
                }
            ],
            yAxis: [
                {
                    type: 'value'
                }
            ],
            series: [
                {
                    name: '实施率(%)',
                    type: 'bar',
                    data: yData, 
                    itemStyle:{
                        normal:{
                            color: '#3aa5e3', // function (value){ return "#"+("00000"+((Math.random()*16777215+0.5)>>0).toString(16)).slice(-6); },
                            label: {
                                show:true, position:'top'
                            }
                        }
                    },
    //                markPoint: {
    //                    data: [
    //                        { name: '年最高', value: 182.2, xAxis: 7, yAxis: 183, symbolSize: 18 },
    //                        { name: '年最低', value: 2.3, xAxis: 11, yAxis: 3 }
    //                    ]
    //                },
                    markLine: {
                        data: [
                            { type: 'average', name: '平均值' }
                        ]
                    }
                }
            ]
        };
        divBar.setOption(option);
    }
    View Code

     十九、Json to String

    function json2str(o) {  
        var arr = [];  
        var fmt = function(s) {  
            if (typeof s == 'object' && s != null) return json2str(s);  
            return /^(string|number)$/.test(typeof s) ? "'" + s + "'" : s;  
        }  
        for (var i in o) arr.push("'" + i + "':" + fmt(o[i]));  
        return '{' + arr.join(',') + '}';  
    }  
    View Code

     二十、获取参数Json

    var getRequest = function () {
        var param, url = location.search, theRequest = {};
        if (url.indexOf("?") != -1) {
            var str = url.substr(1);
            strs = str.split("&");
            for (var i = 0, len = strs.length; i < len; i++) {
                param = strs[i].split("=");
                theRequest[param[0]] = decodeURIComponent(param[1]);
            }
        }
        return theRequest;
    };
    View Code
     

    出处: http://www.cnblogs.com/windy2008

  • 相关阅读:
    mui的相关知识
    4. 本地的json格式调用方法
    DOM树节点的相关知识
    3.函数引用中“值传参”与“引用传参”的区别
    一,数组的创建 数组的遍历
    重载<<
    SendMessage、PostMessage、PeekMessage、GetMessage、PreTreslateMessage等
    TranslateMessage
    怎样在整个类中恒定常量
    格式化输出
  • 原文地址:https://www.cnblogs.com/windy2008/p/1812274.html
Copyright © 2011-2022 走看看