2016-09-27 53 views
0

爲什麼addEventListener不能用於這個項目?

document.getElementById('btn').addEventListener("onclick", mouseover); 
 

 
function mouseover() { 
 
    this.style.color = " yellow "; 
 
    this.style.backgroundcolor = "green"; 
 
}
<input type="button" value= "Submit" id="btn" />

+3

'background.color'應該是'.backgroundColor'。除此之外,誰知道。你沒有給出一個完整的例子。 – 2016-09-27 23:25:12

+2

查看瀏覽器中的開發者控制檯。 – epascarello

+1

它'的addEventListener( 「點擊」,鼠標懸停);' – adeneo

回答

2

要將監聽器附加到名爲點擊一個事件,你需要做以下之一:

object.onclick = function(event) { ... } 
object.addEventListener('click', function(event) { ... }); 

在事件發生前有沒有 「上」名稱在第二種方法,所以在你的情況下,你的代碼應該是:

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,並且應該有顏色的字符串中不能包含空格。)

+0

很好的解釋。請記住,'background.color'仍然是錯誤的,它必須是'backgroundColor。 – JHolub

+0

@JHolub感謝您的更正,修正! – Frxstrem

+0

謝謝你,我明白了 – brandker

1

你有幾個問題,評論解釋什麼是錯的。

//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>

0

嘗試使用的只是click代替onclick

btn.addEventListener("click", mouseover); 

function mouseover() { 
    this.style.color = " yellow "; 
    this.style.backgroundColor = "green";   
} 

此外,上面的意見是正確的,從Javascript到參考背景色用style.backgroundColor

相關問題