簡體   English   中英

EventListener 只觸發一次

[英]EventListener Only Firing Once

仍在學習 JS 的基礎知識,現在使用 EventListeners。 嘗試制作一個來回更改文本顏色的按鈕,但我認為我誤解了該方法的性質,或者使用不正確。 我不相信這是語法問題。

我有文本和按鈕,都帶有 ID。 我為這兩個元素創建了變量。 我為按鈕添加了一個事件監聽器,並在 function 中定義了 if else 語句。 function 的“if”部分執行沒有問題,但這就是它結束的地方。 提前對格式表示抱歉,我不確定什么是最有意義的。 謝謝!

這是 HTML:

<h1 id="header"> Here's some text </h1>

<button id="button"> Change the Color </button>

CSS:

#header {
    color: red;
  }

和 JavaScript:

var header = document.getElementById("header");

var button = document.getElementById("button");

button.addEventListener("click", function() {

  if (header.style.color = "red")   

{header.style.color = "blue";} 

else if (head.style.color = "blue")
{header.style.color = "red";
  }
})

在 JavaScript (和其他語言)中,您需要使用==來檢查是否相等。

但是,在 JavaScript 中也有=== ===嚴格的相等運算符,這意味着它不進行類型轉換。 這意味着什么? 它的意思是:

"5" == 5 // true, since "5" as a number is equal to 5, the literal number

"5" === 5 // false, since a string cannot equal a number

因此,在您的 if 語句中,您應該使用=====而不僅僅是=

其他人提到使用= vs == vs === - 這絕對是你的問題,但你也會有其他問題來比較 styles 的方式。

style屬性獨特且繁瑣。 您有“樣式”屬性,它是 DOM 節點的屬性(就像用於錨點的href或用於輸入的type )。 然后你有 styles 從樣式表應用 - <style>標記或外部樣式表文件。 有時兩個不同的 styles 源會發生沖突。

對於樣式屬性,您可以像現在一樣閱讀node.style.color屬性。 要獲得應用於節點的實際顏色,您必須使用window.getComputedStyle() 讓我通過示例來解釋差異:

 const div = document.getElementById('foo') div.style.color; //-> red window.getComputedStyle(div).color; //-> rbg(0, 255, 0)
 #foo { color: green !important }
 <div id="foo" style="color: red">Hello!</div>

請注意我們如何在節點本身上設置red ,但在樣式表中設置green !important !important將獲勝,這就是文本為綠色的原因。 此外,瀏覽器將顏色名稱green轉換為其 RGB 等效rgb(0, 255, 0) 協調起來可能很乏味。 我通常建議使用多個 class 名稱並在單擊時在這些名稱之間切換:

 var header = document.getElementById("header"); var button = document.getElementById("button"); button.addEventListener("click", function() { if (header.classList.contains("red")) { header.classList.remove("red") header.classList.add("blue") } else if (header.classList.contains("blue")) { header.classList.remove("blue") header.classList.add("red") } })
 .red { color: red }.blue { color: blue }
 <h1 id="header" class="red"> Here's some text </h1> <button id="button"> Change the Color </button>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM