JS常用

  1. 作者QQ:67065435 QQ群:821635552

  2. 判断是否在微信内

    //微信内有自己的一套JS接口,判断接口是否存在即可(比UA判断更有效)
    if (typeof window.WeixinJSBridge === 'undefined') {
        console.log('非微信');
    } else {
        console.log('是微信');
    }
    
  3. 立即执行函数

    (function () {})()
    (function () {}())
    
  4. rem值初始化

     (function () {
         var width = document.documentElement.clientWidth;
         document.documentElement.style.fontSize = width / 7.5 + "px";
     }());
     window.onload = function () {
         var width = document.documentElement.clientWidth;
         document.documentElement.style.fontSize = width / 7.5 + "px";
     };
     window.onresize = function () {
         var width = document.documentElement.clientWidth;
         document.documentElement.style.fontSize = width / 7.5 + "px";
     };
    
  5. foreach

    var arr = [
        a = 1,
        b = 2
    ];
    var sum = 0;
    arr.forEach(function(val,key,arr){
      console.log(arr[key] === val);
      sum += val;
    });
    console.log(sum);
    
  6. 对象转json字符串

    var obj = [{"name":"dog","age":10},{"name":"cat","age":8}];
    var str = JSON.stringify(obj);
    console.log(obj[0].name);
    console.log(obj[1].age);
    console.log(str);
    
  7. json字符串转对象

    var str = '[{"name":"dog","age":10},{"name":"cat","age":8}]';
    var obj = JSON.parse(str);
    console.log(obj[0].name);
    console.log(obj[1].name);
    console.log(str);
    
  8. js时间转日期(自动处理为用户系统设定时区的时间)

    var i,str;
    var date=new Date(1488002361000);
    var arr=[
    date.getFullYear(),
    date.getMonth()+1,
    date.getDate(),
    date.getHours(),
    date.getMinutes(),
    date.getSeconds()
    ];
    for(i=1;i<=5;i++){
        arr[i]=("0"+arr[i]).slice(-2);
    }
    str=arr[0]+'-'+arr[1]+'-'+arr[2]+' '+arr[3]+':'+arr[4]+':'+arr[5];
    console.log(str);
    
  9. js文本转声音

    var text = "我应该说点什么?";
    var speech = new window.SpeechSynthesisUtterance();
    speech.lang = "zh-CN";          //语言
    speech.text = text;             //内容
    speech.rate = 4;                //语速[0,10]
    speech.pitch = 1;               //音频[0,2]
    speech.volume = 1;              //音量[0,1]
    
    speech.onmark = null;
    speech.onpause = null;
    speech.onresume = null;
    speech.onboundary = null;
    
    speech.onstart = null;
    speech.onerror = null;
    speech.onend = null;
    
    window.speechSynthesis.speak(speech);
    
  10. js区块拖动

    <style>
        * {
            margin: 0;
            padding: 0
        }
        #user_cover {
            position: fixed;
            top: 40%;
            right: 0;
            width: 4rem;
            height: 4rem;
            background-color: rgba(0, 0, 0, 0.3);
        }
    </style>
    <div id="user_cover"></div>
    <script>
        //手机拖动
        function onTouchMove(point) {
            document.getElementById('user_cover').style.top = (point.changedTouches[0].clientY) + "px";
            document.getElementById('user_cover').style.left = (point.changedTouches[0].clientX) + "px";
        }
        document.getElementById('user_cover').addEventListener('touchmove', onTouchMove, false);
        //电脑拖动
        function onMouseDown(point) {
            document.onmousemove = function (event) {
                document.getElementById('user_cover').style.top = event.clientY + "px";
                document.getElementById('user_cover').style.left = event.clientX + "px";
                console.log(point);
                console.log(event);
            };
            document.onmouseup = function () {
                document.onmousemove = null;
                document.onmouseup = null;
            };
        }
        document.getElementById('user_cover').addEventListener('mousedown', onMouseDown, false);
    </script>
    
  11. 如何使用JSONP

    (function () {
        var show = function (obj) {
            var body = document.body;
            body.innerHTML = obj.data;
        };
        var url = "https://localhost?fun=show";
        var script = document.createElement('script');
        script.setAttribute('src', url);
        document.getElementsByTagName('head')[0].appendChild(script);
    })()
    
  12. https://localhost?fun=show的响应(JSONP)

    show(
        {
          'code':200,
          'data':'data',
          'msg':'获取数据成功'
        }
    )
    
  13. GET(normal)

    var url='https://localhost?a=1&b=2';
    var ajax=new XMLHttpRequest();
    ajax.open("GET", url, true);
    ajax.withCredentials=true;
    ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    ajax.send();
    ajax.onreadystatechange = function () {
        if (ajax.readyState == 4 && ajax.status == 200) {
            document.body.innerHTML = ajax.responseText;
        }
    }
    
  14. POST(normal)

    var url='https://localhost';
    var ajax=new XMLHttpRequest();
    ajax.open("POST", url, true);
    ajax.withCredentials=true;
    ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    ajax.send("a=1&b=2");
    ajax.onreadystatechange = function () {
        if (ajax.readyState == 4 && ajax.status == 200) {
            document.body.innerHTML = ajax.responseText;
        }
    }
    
  15. POST(json)

    var url='https://localhost';
    var ajax=new XMLHttpRequest();
    ajax.open("POST", url, true);
    ajax.withCredentials=true;
    ajax.setRequestHeader("Content-type", "application/json");
    ajax.send('{"a":1,"b":2}');
    ajax.onreadystatechange = function () {
        if (ajax.readyState == 4 && ajax.status == 200) {
            document.body.innerHTML = ajax.responseText;
        }
    }
    
  16. POST(兼容IE的XHR)

    var url='https://localhost';
    var ajax;
    if (window.XMLHttpRequest) {
        ajax = new XMLHttpRequest();
    } else {
        ajax = new ActiveXObject("Microsoft.XMLHTTP");
    }
    ajax.open("POST", url, true);
    ajax.send('a=1&b=2');
    ajax.onreadystatechange = function () {
        if (ajax.readyState == 4 && ajax.status == 200) {
            document.body.innerHTML = ajax.responseText;
        }
    }
    
  17. POST(异步文件上传)

    var url='https://localhost';
    var upload=document.my_form.my_file;
    upload.onchange=function (event) {
        var file=event.target.files[0];
        var form_data=new FormData();
        form_data.append('file_id', 123);
        form_data.append('my_file', file);
        var ajax=new XMLHttpRequest();
        ajax.withCredentials=true;
        ajax.open('POST', url, true);
        ajax.send(form_data);
        ajax.onreadstatechange=function () {
            if (ajax.readySate==4 && ajax.status==200) {
                document.body.innerHTML = ajax.responseText;
            }
        }
    }
    
Copyright © 豆包嘿嘿~ 2012-∞ 冀ICP备17033181号 all right reserved,powered by Gitbook修订: 2020-06-17 17:22:24

results matching ""

    No results matching ""