您的当前位置:首页>全部文章>文章详情
通过js实现button按钮间隔一分钟可点击
发表于:2022-01-28 14:52:07浏览:1482次TAG: #javascript

设置属性 disabled 可以限制交互,单击按钮时添加disabled=“disabled”属性,再为按钮添加定时器,一定时间后删除定时器和disabled属性。

<!DOCTYPE html><html lang="en"><head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title></head><body>
    <button id='but'> 发送 </button>
    <script data-src="https://cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script>
    <script>
        $(function() {
            $('#but').click(function() {
                $(this).attr("disabled", "disabled");                var id = 10;                //定时执行
                var timeing = setInterval(function() {
                    id = id - 1;
                    $('#but').html(id + 's');
                }, 1000);                //延迟执行
                window.setTimeout(function() {                    //结束定时,恢复按钮可用
                    clearInterval(timeing);
                    $('#but').html('发送').removeAttr("disabled");
                }, 10000);
            });
        });    </script></body></html>

或者用DOM

<script>
        var but = document.getElementById('but');
        but.addEventListener('click', function() {
            var id = 10;
            var attr = document.createAttribute("disabled");
            attr.nodeValue = "disabled";
            //设置节点属性
            but.attributes.setNamedItem(attr);
            var timeing = setInterval(function() {
                id = id - 1;
                but.innerHTML = id + 's';
            }, 1000);
            window.setTimeout(function() {
                clearInterval(timeing);
                but.innerHTML = '发送';
                //移除节点属性
                but.attributes.removeNamedItem('disabled');
            }, 10000);
        });
</script>