0
点赞
收藏
分享

微信扫一扫

使用js代码如何触发回车事件

落花时节又逢君to 2022-04-13 阅读 30

话不多说,直接上代码

<!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>
    <input type="text" id="input">
    <button id="btn">123</button>
<body>
    <script>
        var input = document.querySelector('#input')
        var btn = document.querySelector('#btn')

        input.addEventListener('keydown',function(e){
            console.log(e.which);
            input.value = new Date().toLocaleString()
        })

        btn.addEventListener('click',function(){
            let myEvent = document.createEvent('Event')
            myEvent.initEvent('keydown', true, false)
            console.log(event);
            myEvent = Object.assign(myEvent, {
                ctrlKey: false,
                metaKey: false,
                altKey: false,
                which: 13,
                keyCode: 13,
                key: 'Enter',
                code: 'Enter'
            })
            input.dispatchEvent(myEvent)
        })
    </script>
</body>

</html>
举报

相关推荐

0 条评论