至尊技术网 - js https://www.zzwws.cn/tag/js/ zh-CN Wed, 14 Sep 2022 14:59:00 +0800 Wed, 14 Sep 2022 14:59:00 +0800 js使用window.onload覆盖问题的解决方法 https://www.zzwws.cn/archives/6364/ https://www.zzwws.cn/archives/6364/ Wed, 14 Sep 2022 14:59:00 +0800 悠悠楠杉 解决多人开发时,同时使用window.onload事件所出现的后面的window.onload函数覆盖前面一个window.onload函数的问题。

<script>
    // 第一种,使用addEventListener
    window.onload = function () {
        console.log("第一次调用");
    }

    function twofunction() {
        console.log("第二次调用");
    }
    window.addEventListener("load",twofunction);

    // 第二种,封装window.onload,使用addLoadEvent,但直接使用window.onload还是会被替换的
    function addLoadEvent(func) {
        var oldonload = window.onload;
        if (typeof window.onload != 'function') {
            window.onload = func;
        } else {
            window.onload = function () {
                oldonload();
                func();
            }
        }
    }

    //测试
    addLoadEvent(function () { console.log(1) });
    addLoadEvent(function () { console.log(2) });
    addLoadEvent(function () { console.log(3) });

    // window.onload = function () { console.log(4) }// 上面的addLoadEvent会被替换
</script>
]]>
0 https://www.zzwws.cn/archives/6364/#comments https://www.zzwws.cn/feed/tag/js/
原生js封装ajax https://www.zzwws.cn/archives/6358/ https://www.zzwws.cn/archives/6358/ Sat, 03 Sep 2022 11:46:00 +0800 悠悠楠杉 function ajax(options) { var xhr = null; var type = 'GET'; var params = formsParams(options.data); if(typeof options.type != 'undefined'){ type = options.type.toUpperCase(); } //创建对象 if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } else { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } if (typeof options.async == "undefined") { options.async = true; } // 处理请求成功的回调函数 xhr.onload = function(){ if (xhr.status >= 200 && xhr.status < 300) { if (typeof options.datatype == "undefined" || options.datatype == "json") { if(typeof options.success === 'function'){ options.success(JSON.parse(xhr.responseText)); } } else { if(typeof options.success === 'function'){ options.success(xhr.responseText); } } } else { if(typeof options.error === 'function'){ options.error(xhr.statusText); } } } // 处理请求错误的回调函数 xhr.onerror = function() { if(typeof options.error === 'function'){ options.error(xhr.statusText); } } // 设置请求头部 if (options.headers) { for (var header in options.headers) { xhr.setRequestHeader(header, options.headers[header]); } } // 设置请求方法、URL、是否异步、发送请求 if (type == "GET") { xhr.open(type, options.url + "?" + params, options.async); xhr.send(null); } else if (type == "POST") { xhr.open(type, options.url, options.async); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.send(params); } function formsParams(data) { var arr = []; for (var prop in data) { arr.push(prop + "=" + data[prop]); } return arr.join("&"); } } // 使用 ajax({ url: "api.php",// 请求地址 type: "POST",// 请求方式 async: true,// 同步:false,异步:true,默认为true datatype: "json",// 返回数据的格式,"json","text",默认为json headers: {},// 设置请求头部,{"token": "123456"} data: {// post数据 code: "s2sdd", link: location.href }, success: function (res) {// 处理请求成功 console.log(res); }, error: function (res) {// 处理请求错误 console.log(res); } }) ]]> 0 https://www.zzwws.cn/archives/6358/#comments https://www.zzwws.cn/feed/tag/js/ js执行提示Uncaught URIError: URI malformed https://www.zzwws.cn/archives/6342/ https://www.zzwws.cn/archives/6342/ Mon, 06 Jun 2022 22:50:00 +0800 悠悠楠杉 由于decodeURI转码时,通过%进行解析,如果字符串中存在%则会出现URI malformed

解决方法
将字符串中的%替换为25%就行了

var str = '1%2';
if(str.indexOf('%') > -1) {
    str = str.replace(/%/g,'%25');
}
]]>
0 https://www.zzwws.cn/archives/6342/#comments https://www.zzwws.cn/feed/tag/js/
JQuery长按事件 https://www.zzwws.cn/archives/6341/ https://www.zzwws.cn/archives/6341/ Sat, 21 May 2022 15:44:00 +0800 悠悠楠杉 $(".text").on({ touchstart: function(e) { var oSpan = e.currentTarget.lastElementChild // 长按事件触发 timeOutEvent = setTimeout(function() { timeOutEvent = 0; console.log('你长按了'); }, 500); }, touchmove: function() { clearTimeout(timeOutEvent); timeOutEvent = 0; }, touchend: function() { clearTimeout(timeOutEvent); if (timeOutEvent != 0) { console.log('你点击了'); } return false; } }) ]]> 0 https://www.zzwws.cn/archives/6341/#comments https://www.zzwws.cn/feed/tag/js/ js实现html导出为PDF文件 https://www.zzwws.cn/archives/6336/ https://www.zzwws.cn/archives/6336/ Mon, 04 Apr 2022 13:17:00 +0800 悠悠楠杉 html2canvas官网:http://html2canvas.hertzen.com/

<?php
if(!empty($_POST['datauri'])){
    if(preg_match('/data:.*?;base64,/i',$_POST['datauri'])){
        $datauri = base64_decode(preg_replace('/data:.*?;base64,/i','',$_POST['datauri']));
        $dir = 'upload/';
        if(!is_dir($dir)){
            mkdir($dir);
        }
        $file = md5($_SERVER['HTTP_USER_AGENT'] . $_SERVER['REMOTE_ADDR']).'.pdf';
        try {
            file_put_contents($dir.$file,$datauri);
            $data = ['code' => 1,'msg' => '上传成功','url' => $dir.$file];
        } catch (Exception $e) {
            $data = ['code' => 0,'msg' => '上传失败'];
        }
        echo json_encode($data);exit();
    }
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div id="content">内容</div>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.0.272/jspdf.debug.js"></script>
    <script>
        $(".download").on('click', function() {
            downLoadPdf(document.getElementById("content"));
            //downloadQrCode(document.getElementById("content"));
        })
        //保存为jpg图片
        function downloadQrCode(content) {
            html2canvas(content).then(function(canvas) {
                var img = document.createElement('a');
                img.href = canvas.toDataURL("image/jpeg",1);
                img.download = 'report.jpg';
                img.click();
            });
        }
        //保存为PDF文件
        function downLoadPdf(content) {
            content = content ? content : null;
            // 条件判断是否打印
            if (!content) {
                alert("打印失败,请重新操作")
                return false
            }

            html2canvas(content, {
                allowTaint: true,
                useCORS: true
            }).then(function(canvas) {
                var pdfWidth = canvas.width;
                var pdfHeight = canvas.height;
                var pageHeight = pdfWidth / 592.28 * 841.89;
                var leftHeight = pdfHeight;
                var position = 0;
                var imgWidth = 595.28;
                var imgHeight = 595.28 / pdfWidth * pdfHeight;
                var pageData = canvas.toDataURL("image/jpeg",1);
                var pdf = new jsPDF('', 'pt', 'a4');
                // 判断打印dom高度是否需要分页,如果需要进行分页处理
                if (leftHeight < pageHeight) {
                    pdf.addImage(pageData, "jpeg", 0, 0, imgWidth, imgHeight)
                } else {
                    while (leftHeight > 0) {
                        pdf.addImage(pageData, "jpeg", 0, position, imgWidth, imgHeight)
                        leftHeight -= pageHeight
                        position -= 841.89
                        if (leftHeight > 0) {
                            pdf.addPage()
                        }
                    }
                }
                //pdf.save("report.pdf");//下载PDF
                var datauri = pdf.output('dataurlstring'); //base64编码
                //上传
                $.post('', {
                    datauri
                }, function(res) {
                    if (res.code == 1) {
                        window.open(res.url);
                    } else {
                        alert('获取PDF文件失败');
                    }
                }, 'json')
            })
        }
        // js计算base64图片大小
        function imageSize(base64Str) {
            const indexBase64 = base64Str.indexOf('base64,');
            if (indexBase64 < 0) return -1;
            const str = base64Str.substr(indexBase64 + 6);
            return (str.length * 0.75 / 1000).toFixed(2);
        }
    </script>
</body>

</html>
]]>
0 https://www.zzwws.cn/archives/6336/#comments https://www.zzwws.cn/feed/tag/js/
JS实现随机抽奖功能 https://www.zzwws.cn/archives/6321/ https://www.zzwws.cn/archives/6321/ Tue, 18 Jan 2022 13:31:38 +0800 悠悠楠杉

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .container {
            width: 600px;
            height: 600px;
            border: 1px solid;
            display: flex;
            flex-wrap: wrap;
            margin: 100px auto;
        }

        .block {
            width: 33.33%;
            height: 33.33%;
            outline: 1px solid black;
            text-align: center;
            line-height: 200px;
            font-size: 26px;
        }

        .block5 {
            background-color: skyblue;
            cursor: pointer;
        }
    </style>
</head>
<body>
     <div class="container">
        <div class="block1 block">小米笔记本</div>
        <div class="block2 block">iPhoneX</div>
        <div class="block3 block">PS4游戏机</div>
        <div class="block4 block">谢谢参与</div>
        <div class="block5 block">开始抽奖</div>
        <div class="block6 block">索尼电视机</div>
        <div class="block7 block">西门子冰箱</div>
        <div class="block8 block">老板抽油烟机</div>
        <div class="block9 block">空气净化机</div>
    </div>
    <script>
        var blocks = document.getElementsByClassName("block");
        // 数组存放的是盒子的下标,按照顺时针的顺序
        var arr = [0, 1, 2, 5, 8, 7, 6, 3], i = 0, count = 0, stopTimer;
        var rand = Math.floor(Math.random() * 8 + 50); // 给出一个停止计时器的随机数 count的值等于这个随机数时停止计时器
        var around = function () {
            // 将其他盒子都变为白色
            for (var j = 0; j < arr.length; j++) {
                blocks[arr[j]].style.background = "white";
            }
            // 这里blocks的取值为 blocks[0] blocks[1] blocks[2] blocks[5] blocks[8] blocks[7] blocks[6] blocks[3]
            // 将当前arr[i]值所对应的盒子修改为粉色
            blocks[arr[i]].style.background = "pink";
            i++; 
            // 重制i的值
            if (i === arr.length) {
                i = 0;
            }
            count++; // count是一个计数器 根据count的值来调整速度
            // 下面的4个if根据count的值来关闭计时器和重启计时器 改变计时器的时间间隔
            if (count === 5 || count === 45) {
                clearInterval(stopTimer);
                stopTimer = setInterval(around, 200);
            }
            if (count === 10 || count === 35) {
                clearInterval(stopTimer);
                stopTimer = setInterval(around, 100);
            }
            if (count === 15) {
                clearInterval(stopTimer);
                stopTimer = setInterval(around, 50);
            }
            // 当等于上面的随机数时,停止计时器
            if (count === rand) {
                clearInterval(stopTimer);
            }
        }
        // 给开始按钮绑定点击事件 点击后执行 around 
        var start = function () {
            blocks[4].removeEventListener("click", start); // 当用户点击了开始按钮后 必须要移除该事件 防止用户重复点击
            stopTimer = setInterval(around, 300);
        }
        blocks[4].addEventListener("click", start);
    </script>
</body>
</html>

]]>
0 https://www.zzwws.cn/archives/6321/#comments https://www.zzwws.cn/feed/tag/js/
关于&amp;notify_url变成¬ify_url的解决方法 https://www.zzwws.cn/archives/6313/ https://www.zzwws.cn/archives/6313/ Sat, 25 Dec 2021 11:44:00 +0800 悠悠楠杉 在页面上显示&notify_url不管怎样都变成¬ify_url,后来发现把&改为&amp就可以了

PHP字符替换

$str = '&notify_url';
$url = str_replace("&","&amp",$str);

js字符替换

str = '&notify_url';
url = str.replace(/&/, "&amp");
]]>
0 https://www.zzwws.cn/archives/6313/#comments https://www.zzwws.cn/feed/tag/js/
js判断数组中是否存在某个元素 https://www.zzwws.cn/archives/6174/ https://www.zzwws.cn/archives/6174/ Thu, 02 Dec 2021 10:28:18 +0800 悠悠楠杉 方法一:array.indexOf(item,start)

实际用法:if(arr.indexOf(某元素) > -1){//则包含该元素}

var fruits = ["Banana", "Orange", "Apple", "Mango"];
var a = fruits.indexOf("Apple"); // 2

方法二:array.find()

arr = [1,2,3,4,5];
arr.find(function(value) {
    if(value === 要查找的值) {
    //包含该元素
    }
})

方法三:jQuery.inArray()

arr = [1,2,3,4,5];
index = $.inArray(2,arr);
if(index > -1){
    console.log('包含该元素')
}
]]>
0 https://www.zzwws.cn/archives/6174/#comments https://www.zzwws.cn/feed/tag/js/
js获取时间戳,时间戳格式化日期 https://www.zzwws.cn/archives/6135/ https://www.zzwws.cn/archives/6135/ Thu, 25 Nov 2021 23:06:00 +0800 悠悠楠杉 js获取当前时间戳的方法

var timestamp = Date.parse(new  Date())/1000;//获取当前秒的时间戳
var timestamp = (new Date()).valueOf();//获取当前毫秒的时间戳
var timestamp = new Date() . get Time();//返回数值单位是毫秒

js获取指定时间戳的方法

var timestamp = (new Date(" 2021/11/25 20:00:20")).getTime()/1000;

格式化日期

function dateFormat(thisDate, fmt) {
    var o = {
        "M+": thisDate.getMonth() + 1,
        "d+": thisDate.getDate(),
        "h+": thisDate.getHours(),
        "m+": thisDate.getMinutes(),
        "s+": thisDate.getSeconds(),
        "q+": Math.floor((thisDate.getMonth() + 3) / 3),
        "S": thisDate.getMilliseconds()
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (thisDate.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 Date=new Date();
console.log(dateFormat(Date, "yyyy-MM-dd hh:mm:ss"))//调用

计算当前日期的星期一与星期天

var Date=new Date();
var selectTime = Date.getTime();//获取时间戳
var selectDay = Date.getDay();//获取星期
var oneDayLong = 24 * 3600 * 1000;//定义一天有多少毫秒
var MondayTime = selectTime - (selectDay - 1) * oneDayLong;
var monday = new Date(MondayTime)//时间戳再转回时间
var SundayTime = selectTime - (selectDay - 7) * oneDayLong;
var sundayTime = new Date(SundayTime)
console.log(monday)
console.log(sundayTime)

计算某一日期是星期几

当我们知道某一'yyyy-mm-dd'日期时便可以计算出当前是星期几,公式如下:

基姆拉尔森计算公式

W= (d+2*m+3*(m+1)/5+y+y/4-y/100+y/400) mod 7

在公式中d表示日期中的日数,m表示月份数,y表示年数。(其中mod意思是取余计算,js用的是%)

]]>
0 https://www.zzwws.cn/archives/6135/#comments https://www.zzwws.cn/feed/tag/js/
页面加载时增加loading效果 https://www.zzwws.cn/archives/5819/ https://www.zzwws.cn/archives/5819/ Mon, 20 Sep 2021 11:48:00 +0800 悠悠楠杉 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> #loading { position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: 2000; opacity: 1; background: #f7f7f7; } #loading img { width: 200px; height: 200px; position: absolute; top: 50%; left: 50%; margin-top: -100px; margin-left: -100px; z-index: 999; } </style> </head> <body> <div id="loading"><img src="loading.gif" id="loading"></div> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> //监听加载状态改变 document.onreadystatechange = completeLoading; //加载状态为complete时移除loading效果 function completeLoading() { if (document.readyState == "complete") { $("#loading").animate({ "opacity": "0" }, 500).hide(1000); } } </script> </body> </html> ]]> 0 https://www.zzwws.cn/archives/5819/#comments https://www.zzwws.cn/feed/tag/js/