按下空格键时触发按钮单击(网页)

时间:2019-04-21 21:53:08

标签: javascript html css

我的网页上有一个按钮,当用户用鼠标单击时以及击中空格键时,都需要触发该按钮,这甚至是一件事情吗?

HTML

<div class="col-12 button small-button">
       <a onclick="generator()">
            <img src="icones%20web%20projeto.png" title="Descubra um novo artista" alt="New Image">
       </a>
</div>

JS

function generator() {
    var x= Math.floor((Math.random()*35)+1);
    console.log(x);
    document.getElementById('divImage').innerHTML='<img src="img/'+x+'.png">';
 }

1 个答案:

答案 0 :(得分:0)

不使用任何第三方库。

document.body.onkeydown = function(e){
    if (e.keyCode == 32) {
        // add your code here.
        console.log('Space pressed');
    }
}

或使用addEventListener()方法:

window.addEventListener('keydown', function(e) {
    if (e.keyCode == 32) {
        // add your code here.
        console.log('Space pressed');
    }
});

相关问题