JS常用

  1. 作者QQ:67065435 QQ群:821635552

  2. 本站内容全部为作者原创,转载请注明出处!

  3. 判断是否在微信内

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

    (function () {})()
    (function () {}())
    
  5. 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";
     };
    
  6. 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);
    
  7. 对象转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);
    
  8. 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);
    
  9. 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);
    
  10. 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);
    
  11. 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>
    
  12. JS文本转图片

    <meta charset="UTF-8">
    <div id="box"></div>
    <script>
        var str = `夏季的阳光非常毒辣,太阳才刚升起没多久,炽热的光线就像黄蜂的尾巴一样蛰人。魔兽联军赶到瓦伦关下后,不作半点停歇,立刻就发动了攻击。
    无数的兵马发出山呼海啸的呐喊,黑云压城般地猛扑而来。刀剑的反光,士兵的杀声,野兽的吼叫,充满了天地之间。在这份压力的逼迫下,连城墙背后的日不落山都开始颤抖起来。
    “我现在的感受,大概也就是昨天保卫瓦伦关的雅尔塔心中的感受吧。”与我一战之后雅尔塔就不知所踪,再也没有出现过。他受的伤和我一样重,但身体的自我回复能力却远不如我,估计现在一定是躲在哪个茅坑里偷偷地养伤。
    魔兽联军的混合部队夹杂在一起向千疮百孔的城墙发动了猛烈的冲击。城墙下挤满了千军万马,陪我一起断后的部队仅数千人而已,而且都已一天一夜没有睡过觉了,我们所能倚仗的也只是一段破了好几个大洞的城墙。
    唯一的让我感到安慰的是魔兽联军仓促地赶到这里,亦是一支筋疲力尽的疲兵,而且他们缺少攻城装备。我们攻城时遗弃在城外的装备在魔兽联军赶到战场之前就已被破坏,这方面我们还稍微占着一点地利优势。
    “放箭!放箭!”
    面对潮水般涌上的敌人,所有的守城士兵全都擎起大弓射箭。箭如雨下,魔兽联军象被收割的麦子一样倒下,昨天躺在这儿睡觉的人类士兵现在有了新床伴。敌人的数量实在是太多了,就算是最差劲的弓箭手在此也成了百发百中的神箭手。
    尽管如此,暴风雨般的箭矢也阻挡不住魔兽联军前进的势头。昨天攻城时被摧毁的几段城墙现在成了魔兽联军的唯一突破口,几个缺口从一开战就成了双方重兵争夺的焦点。
    强壮的牛头怪,手持重兵器的熊人,身披重铠的科摩多龙人,这些擅打硬仗的兵种是强攻的主力。他们红着眼睛,像恶狼一样地嚎叫着,拼命地向缺口里填。而人类方面也不是吃素的,缺口处的人类士兵也奋起余勇。
    用血R之躯填补空隙。石块、檑木、弓箭,不断地从缺口两边的城墙上飞下。刀光剑影,血R横飞,双方就在缺口处展开了拉锯式的白刃战。在一片刀光血海中,缺口渐渐地为尸体所填满。城墙两边的尸体都堆得老高。
    不过数米宽的缺口成为一个个无底的黑洞,不停地吞噬着双方士兵的生命。`;
    
        var font_size = 24;         //文字大小(按像素算)
        var font_border = 0;        //文字间距(调整异常)
        var line_border = 10;       //上下行距(按像素算)
    
        var width = 400;            //图片宽度
        var lines = 10;             //图片行数
        var box_border = 16;        //左右边距
    
        var font_color = "#383838"; //文字颜色
        var back_color = "#fafafa"; //图片背景
    
        var length = Math.floor((width - box_border * 2) / (font_size + font_border));//每行字数
    
        //处理内容文本
        str = str.replace(new RegExp(/[^\S\r\n]+/, 'g'), "");
        str = str.trim();
        str = "  " + str.replace(new RegExp(/[\r\n]+/, 'g'), "\n  ");
        str = str.split("\n");
        var ctt = "";
        str.forEach(function (sv, sk) {
            for (var i = 0; i < sv.length; i += length) {
                ctt = ctt + sv.substr(i, length) + "\n";
            }
        });
        ctt = ctt.trim();
        ctt = ctt.split("\n");
        ctt[0] = "  " + ctt[0];
    
        //计算总计行数
        var line_count = ctt.length;
        //计算尾图行数
        var line_end = line_count % lines;
        //计算尾图编号
        var img_end = Math.ceil(line_count / lines);
    
        //底片指针数组
        var back;
        var text = [];
        var image = [];
        var canvas = [];
        //底片存放容器
        var box = document.getElementById('box');
        box.style.backgroundColor = back_color;
        //声明图片高度
        var height;
        ctt.forEach(function (cv, ck) {
            //计算底片编号
            var img_id = Math.ceil((ck + 1) / lines);
            //计算填第几行
            var line = (ck + 1) % lines;
            line = (line !== 0) ? line : lines;
            //首行生成底片
            if (line === 1) {
                //计算底片高度
                if (img_id === img_end) {
                    height = (font_size + line_border * 2) * line_end;
                } else {
                    height = (font_size + line_border * 2) * lines;
                }
                //生成底片资源
                canvas[img_id] = document.createElement('canvas');
                canvas[img_id].width = width;
                canvas[img_id].height = height;
                canvas[img_id].style.width = '100%';
                canvas[img_id].style.height = 'auto';
                if (!back) {
                    back = canvas[img_id].getContext('2d');
                    back.fillStyle = back_color;
                }
                back.fillRect(0, 0, width, height);
            }
            //本行写入底片
            var font_x = box_border;
            var font_y = (font_size + line_border * 2) * line - line_border;
            text[ck] = canvas[img_id].getContext('2d');
            text[ck].fillStyle = font_color;
            text[ck].font = font_size + "px 楷体";
            text[ck].fillText(cv, font_x, font_y);
            //底片放入盒子
            if (
                (line === lines) ||
                (img_id === img_end && line === line_end)
            ) {
                image[img_id] = new Image();
                image[img_id].src = canvas[img_id].toDataURL("image/png");
                image[img_id].style.width = '100%';
                image[img_id].style.height = 'auto';
                box.appendChild(image[img_id]);
            }
        });
    </script>
    <button class="copy" data-clipboard-target="#box" style="width:100%;height:80px;font-size:60px;">复制内容</button>
    <script src="clipboard.min.js"></script>
    <script>
        //clipboard复制内容
        var clipboard = new ClipboardJS('.copy');
        clipboard.on('success', function (e) {
            e.clearSelection();
            console.log("复制成功");
        });
        clipboard.on('error', function (e) {
            e.clearSelection();
            console.log("复制失败");
        });
    </script>
    
  13. 如何使用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);
    })()
    
  14. https://localhost?fun=show的响应(JSONP)

    show(
        {
          'code':200,
          'data':'data',
          'msg':'获取数据成功'
        }
    )
    
  15. 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;
        }
    }
    
  16. 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;
        }
    }
    
  17. 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;
        }
    }
    
  18. 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;
        }
    }
    
  19. 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-08-19 14:05:41

results matching ""

    No results matching ""