简体   繁体   English

使用按钮更改颜色文本

[英]Changing color text using button

I tried changing text color of my html using javascript . 我尝试使用javascript更改html的文本颜色。 After few tries I realised i cant change the color if i am changing it in css. 经过几次尝试,我意识到如果在CSS中更改颜色,则无法更改颜色。 So basically it means CSS is executed at the end?? 所以基本上,这意味着CSS会在最后执行? and how can i change the color of the text after clicking the button if i am changing it in css as well? 如果我也在CSS中更改了按钮,如何在单击按钮后更改文本的颜色? Sorry i am new 对不起,我是新来的

function changecol()
      { 
          var html=document.body;

          html.style.backgroundColor='black';
          html.style.color='white';

      }

Expected all the lines in my html to turn white but only those where i have not applied css became white 期望我的html中的所有行都变成白色,但是只有那些我未应用CSS的行才变成白色

This is a jquery approach, that will change your color on button click: 这是一种jQuery方法,将在单击按钮时更改颜色:

 $("#butt").on("click",function(){ $(".color").css("background-color","red"); $(".color").css("color","white"); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="color">HALLO</div> <button id="butt">Change Color</button> 

You are probably dealing with an inheritance problem. 您可能正在处理继承问题。 In your case, you are putting a style on the body, and the only elements that inherit styles from the body are ones without their own style. 在您的情况下,您要在主体上放置样式,并且唯一从主体继承样式的元素是没有样式的元素。 To solve this, I recommend applying the style directly to each element. 为了解决这个问题,我建议直接将样式应用于每个元素。

Try this: 尝试这个:

function changecol(){
  document.body.style.backgroundColor='black';
  document.body.style.color='white';

  // change background color of each element 
  var elements = document.querySelectorAll('*');
  for(let i=0;i<elements.length;i++){
    elements[i].style.backgroundColor='black';
    elements[i].style.color='white';
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM