为什么不是't为该项目工作的addEventListener
Why isn't addEventListener working for this project?
document.getElementById('btn').addEventListener("onclick", mouseover);
function mouseover() {
this.style.color = " yellow ";
this.style.backgroundcolor = "green";
}
<input type="button" value= "Submit" id="btn" />
要将侦听器连接到名为的事件,请单击,您需要执行以下操作之一:
object.onclick = function(event) { ... }
object.addEventListener('click', function(event) { ... });
在第二种方法中,事件名称之前没有"on">,因此在您的情况下,您的代码应该是:
var btn = document.getElementById('btn');
btn.addEventListener("click", mouseover);
// ^-- note no "on" here
function mouseover() {
this.style.color = "yellow";
this.style.backgroundColor = "green";
}
<input type="button" value= "Submit" id="btn" />
(还要注意,它是backgroundColor
,而不是background.color
,并且颜色字符串中不应该有空格。(
您有一些问题,注释解释了问题所在。
//define the function first (best practice)
function mouseovera() {
this.style.color = "yellow"; //remove the spaces
this.style.backgroundColor = "green"; //It is camel case not dot
}
var btn = document.getElementById("a");
btn.addEventListener("click", mouseovera); //it is click, not onclick
<button id="a" type="button">a</button>
现在,更好的方法是使用类。使用classList,您可以在单击按钮时轻松切换类或添加类。当您使用一个类时,很容易在JavaScript代码之外维护它们的样式。
function makeActive() {
this.classList.toggle("active")
}
var btn = document.getElementById("a");
btn.addEventListener("click", makeActive);
button {
background-color: #CCC;
}
.active {
color: yellow;
background-color: green;
}
<button id="a" type="button">a</button>
试着只使用click
而不是onclick
。
btn.addEventListener("click", mouseover);
function mouseover() {
this.style.color = " yellow ";
this.style.backgroundColor = "green";
}
此外,上面的评论是正确的,即要引用Javascript中的背景颜色,请使用style.backgroundColor
相关文章:
- 让typescript与facebook登录为Angular 2项目工作
- 引导轮播,修改为显示多个项目.无法正常工作的火狐和IE
- 当控制台不在't在chrome中打开,有些项目不再可点击(有些js调用停止工作)
- 我正试图获得一个带有复选框的多选下拉列表,在填充项目和获得所有选中的工作时遇到了一些问题
- javascript函数没有'不能在MVC项目下工作
- simple{{}}不在angularJS项目中工作
- 项目获胜'我不在火狐工作
- 单击的第二个项目无法正常工作
- 轨道:-位置.Href 不在项目中工作
- 离子项目,不是在手机上工作,而是在开发过程中工作
- 在angular Webpack工作流演示项目中导入angular Webpack
- 循环时更改数组中项目的样式是't工作
- 我可以'我不能让这个JFidddle代码在我的项目中工作
- 占位符文本在IE中不带项目符号.使用chrome可以很好地工作
- 了解eclipse项目的性质和web开发的工作流程
- 当项目停止在.NET中运行时,有没有办法阻止web方法工作
- 我试图创建一个简单的angularjs项目,但ng-view不工作
- 我需要做些什么才能让账户进入我的流星项目工作
- CheckBoxList检查所有项目,点击只工作一次
- 为什么不是't为该项目工作的addEventListener