繁体   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