简体   繁体   中英

Javascript If/else style changing

I have a problem with simple if else statement that changes text color of a <p> element depending on a current color. I see why I get certain results but I can't seem to find a solution. Any help to newbie like me appreciated.

HTML

<p id="demo">JavaScript can change the style of an HTML element.</p>

JS TRY 1

<script> 
var x = document.getElementById("demo");

    function one() {  

x.style.fontSize="16px";
x.style.color="black";}

function two() {

x.style.fontSize="16px";
x.style.color="red";}

function three(){

if(x.style.color="black") { two() }
else {one()
}
}
</script>` <button type="button" onclick="three()">Click Me!</button>

JS TRY 2

<script> 
var brojilo = 1 ;
function three(){ 
 var x = document.getElementById("demo");

function two() {

x.style.fontSize="18px";
x.style.color="red";}

function one() {  

x.style.fontSize="18px";
x.style.color="black";}

if (brojilo % 2 == 0)
{one()} 
else
{two()}

var brojilo = brojilo + 1 ;

}
</script><button type="button" onclick="three()">Click Me!</button>

JS TRY 3

<script> 
var b2 = 0 ;

function brojanje(){
var b2 = b2+1;}

function three(){ 
 var x = document.getElementById("demo");

function two() {

x.style.fontSize="18px";
x.style.color="red";}

vfunction one() {  

x.style.fontSize="18px";
x.style.color="black";}

if (b2 % 2 == 0)
{one()} 
else
{two()}
}
</script><button type="button" onclick="three(); brojanje ();">Click Me!</button>

You can use getComputedStyle to get the element's color.

window.getComputedStyle(x, null).color

Since the value of the color property of your 'demo' element hasn't been initialized, it contains the default value of rgb(0, 0, 0) which corresponds to the color black.

See below for an example of toggling between two colors:

 var black = 'rgb(0, 0, 0)'; var red = 'rgb(255, 0, 0)'; function toggleColor() { var x = document.getElementById("demo"); var currentColor = window.getComputedStyle(x, null).color; if(currentColor === black) { x.style.color = red; } else { x.style.color = black; } } 
 <p id="demo"> JavaScript can change the style of an HTML element. </p> <input type="button" onclick="toggleColor()" value="Toggle Color"> 

u can use a variable to cache current color, for example:

(function(){
  var color = 'red';

  var demoEl = document.getElementById("demo");
  demoEl.addEventListener('click', function(e) {
      if (color === 'red') {
          demoEl.style.color = 'black';
          color = 'black';    // set current color
      } else {
          demoEl.style.color = 'red';
          color = 'red';
      }
  }, false);
})();

<p id="demo">JavaScript can change the style of an HTML element.</p>

使用getComputedStylestyle用于内联CSS。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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