簡體   English   中英

切換按鈕的背景顏色不起作用

[英]toggle background color of the button not working

我一直在嘗試切換按鈕的背景顏色,就像更改邊距一樣,出於某種原因,邊距有效,而btn顏色卻不起作用。

<script>
   let myBtn = document.querySelector("#menuBtn");

   function myFunction1() {
    var Menubase = document.getElementById("list-menu-base");
    if (Menubase.style.marginTop==="0px") {
    Menubase.style.marginTop="-250px";
    } else {
    Menubase.style.marginTop="0px";
      }
    }

myBtn.onclick = myFunction1;

   // The above function works bu not the one follows// 

   function myFunction3() {
  var Menubase = document.getElementById("menuBtn");
  if (Menubase.style.backgroundColor==="red") {
    Menubase.style.backgroundColor="#FF7E00";
  } else {
    Menubase.style.backgroundColor="#FF7E00";
  }
}

myBtn.onclick = myFunction3;
</script>

無論您在每個函數中使用什么代碼。

同一元素不能有兩個onClick事件。

用一個容器函數包裝兩個函數,例如:

function fullFunction() { 
   myFunction1();
   myFunction3();
}
myBtn.onclick = fullFunction;

第二:您應該在JavaScript代碼的rgb添加顏色,而不是hex

演示:

 let myBtn = document.querySelector("#menuBtn"); function myFunction1() { var Menubase = document.getElementById("list-menu-base"); if (Menubase.style.marginTop === "0px") { Menubase.style.marginTop = "25px"; } else { Menubase.style.marginTop = "0px"; } } function myFunction3() { var myBtn = document.getElementById("menuBtn"); if (myBtn.style.backgroundColor === "rgb(142, 253, 27)") { myBtn.style.backgroundColor = "rgb(255, 103, 0)"; } else { myBtn.style.backgroundColor = "rgb(142, 253, 27)"; } } function fullFunction() { myFunction1(); myFunction3(); } myBtn.onclick = fullFunction; 
 #menuBtn { background-color: rgb(255, 103, 0); padding: 10px 15px; text-decoration: none; color: white; margin-top: 100px; } #list-menu-base { background-color: antiquewhite; width: 100%; height: 50px; } 
 <div id="list-menu-base"></div> <a id="menuBtn" href="#">MENU BUTTON</a> 

您需要修復您的js

function myFunction3() {
    var Menubase = document.getElementById("menuBtn");
    // Don't exists red color, so u can try use the rgb
    if (Menubase.css('color') == 'rgb(255, 0, 0)') {
        Menubase.style.backgroundColor = "rgb(255,126,0)";
    } else {
        Menubase.style.backgroundColor = "rgb(255,126,100)";
    }
}

暫無
暫無

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

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