简体   繁体   中英

JavaScript setInterval for outline color flicker not working after first change of color

I'm trying to change the outline color of an H1 element every 2 seconds. So I used this JavaScript code... But it only changes from yellow to orange once and stays at Orange the entire time. What can I do to make it Flicker between the two colors? Please respond in JS terms and not JQuery Library

Here is my JavaScript Code, I'm new to JS :

var myVar = setInterval(function(){ colorFlicker() }, 2000);

function colorFlicker(){
    var y = document.getElementById("mainH1");
    y.style.outlineColor = y.style.outlineColor == "#ff944d" ? "#d9ff66": "#ff944d";
  }

Don't check for colors in javascript, the returned color depends on the browser, and is often in the format rgb(200,33,33) or rgba(244,22,244,1) or even hex in older browsers, use a flag instead

 var myVar = setInterval(colorFlicker, 500); var flag = true; function colorFlicker() { var y = document.getElementById("mainH1"); y.style.outlineColor = flag ? "#d9ff66" : "#ff944d"; flag = !flag; } 
 #mainH1 {outline: 2px solid #ff944d;} 
 <h1 id="mainH1">TEST</h1> 

Use rgb() for the default color then adapt your condition :

 var myVar = setInterval(colorFlicker, 1000); function colorFlicker() { var y = document.getElementById("mainH1"); y.style.outlineColor = y.style.outlineColor == "rgb(255, 148, 77)"?"#d9ff66":"rgb(255, 148, 77)"; } 
 h1 { outline-style: dotted; outline-color: rgb(255, 148, 77); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <h1 id='mainH1'>mainH1</h1> 

Style changes should be handled with CSS. You can then use JavaScript to safely toggle a class that would attach the CSS style to your elements:

/* css */
#mainH1 { outline: /* some color */ }
#mainH1.alternateColor { outline: /* some other color */ }

// JS
var y = document.getElementById("mainH1");
function colorFlicker(){
  y.classList.toggle('alternateColor');
}

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