javascript events, onfocus

javascript events, onfocus

本文关键字:onfocus events javascript      更新时间:2024-03-19

现在我正在更改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关键字,并允许附加其他类似的事件,而无需覆盖它们。

此处的工作示例

通过tabindex为每个要用于焦点的div添加一个类。Tabindexes可以使div聚焦

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

现在您只需添加eventlistener

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';
}