JS 禁止右击,粘贴,手动输入的功能

<script>
    //輸入第一個字符的時間
    var time1 = 0;
    var time2 = 0;
    var textLengthLast = 0;
    var inputEle = document.getElementById("txtData");

    //禁止CtrlV
    inputEle.onkeydown = function (e) {
        var self = null;
        if (e) {
            self = e;
        } else {
            self = window.event;
        }
        if (self.ctrlKey == true && self.keyCode == "86") {
            event.keyCode = 0;
            event.returnValue = false;
            alert("禁止粘貼");
        }
    }

    //禁止手動輸入
    inputEle.onkeyup = function (e) {
        var text = inputEle.value;
        var textLengthNow = text.length;

        if (textLengthNow > textLengthLast) {
            if (time1 == 0) {
                time1 = new Date().getTime();
            } else {
                if (textLengthLast == 0 && textLengthNow == 1) {
                    time1 = new Date().getTime();
                }
                time2 = new Date().getTime();
                if (time2 - time1 > 500) {
                    inputEle.value = "";
                    time1 = 0;
                    time2 = 0;
                    alert("请扫描条码,不可手动输入,违者记过处理!");
                    inputEle.value = "";
                    return;
                }
            }
        }
        textLengthLast = textLengthNow;
    }

    //禁止右鍵
    inputEle.oncontextmenu = function (e) {
        event.keyCode = 0;
        event.returnValue = false;
        alert("禁止右鍵");
    }
</script>

  

posted @ 2021-09-13 19:02  zq爱生活爱代码  阅读(93)  评论(0编辑  收藏  举报