javascript events, onfocus
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
关键字,并允许附加其他类似的事件,而无需覆盖它们。
此处的工作示例
通过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';
}
相关文章:
- 在javascript中传递onmouseenter事件上的onfocus
- Internet Explorer 8. Events
- events javascript
- 通过sdk/system/events在修改请求观测器上测试http
- Javascript events: window.event vs argument reference (funct
- 不使用id的javascript中的onfocus函数
- OnFocus OnBlur with ASP.NET
- Qooxdoo Events 最佳实践
- 在 javascript 中使用 onFocus 显示的消息
- 防止自定义文本出现在页面上的所有高图表上,←使用 {events:{load:function(){var.
- 下个月开始MooTools Events Calendar
- 如何删除/重置window.onfocus函数
- Onblur,Onfocus javascript for TextMode=“MultiLine” 不起作用
- OnFocus Onblur issue JavaScript 多个 instace of 同一字段
- javascript问题后的onblur和onfocus
- javascript events, onfocus
- 使用JavaScript更改onfocus
- Javascript的Onfocus()事件未计算文本框值
- Javascript OnFocus and OnBlue events
- javascript onblur and onfocus events in iPad Safari