javascript 事件,焦点

javascript events, onfocus

现在我正在像这样更改 onfocus(onclick 等)事件的默认行为:

<div onfocus="my(this);"> </div>
function my(e){
    e.style.backgroundColor = "red";//here we do not use getElementById
}

在我需要附加来自 javascript 的事件之前,这一直很好用。当然我们可以使用 addEventListener("focus", my) 但在这种情况下我们不发送 this 值,我需要通过 getElementById 找到它,但这对我不利。我怎么解决这个问题?谢谢

试试这个。将您的 html 更改为:

<div onclick="my(event);"> test</div>

还有你的 JS:

function my(e){
    e.target.style.backgroundColor = "red";//here we do not use getElementById
}

e.target是接收事件的元素。

    document.querySelector("div").addEventListener("click", my, false); //select the only div

    function my(e){
        e.target.style.backgroundColor = "red";//here we do not use getElementById
    }
<div> Test div </div>

Target 是关键字。我仍然会使用 addEventListener,因为它是比内联事件更标准的方法。此外(你现在不需要它)它本机发送 this 关键字并且它允许附加其他类似事件而不覆盖它们。

Working example here

为每个 div 添加一个 class 作为焦点 和 tabindex。 Tabindexes 可以使divs成为焦点

<div class="sofocus" tabindex="0">

现在您只需添加事件监听器

var focusDivs = document.querySelectorAll('.sofocus');
for(var i = 0; i < focusDivs.length; i++){
  var div = focusDivs[i];
}

将每个 div 与事件绑定

div.addEventListener("focus", styleItRed);

也因为不再专注

div.addEventListener("blur", removeColor);

考虑到这一点,您可以创建函数

function styleItRed(){
    this.style.color = 'red';
}

function removeColor(){
    this.style.color = 'inherit';
}