最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I make buttons flash different background colors when clicked - Stack Overflow

programmeradmin4浏览0评论

I am a super noob at this. I have created the following with a bunch of buttons. Two of the buttons are Auto and USA. I want the auto button to flash every color (i.e. red, white, blue, green,black, and any other colors i decide to add as buttons) onClick. I want the USA button to flash only red, white, and blue only, onClick. Also, although there is no CSS in the following I also want to position the buttons where I want them. I tried several things on this site suggesting positioning (i.e.float, absolute, relative) but do not know how to write the CSS for that (does it fall between style tags?). Any and all help would be appreciated.

`<HTML>

   <HEAD>
 <script type = “JavaScript” > 
           function changecolor (code)
            {           
 document.bgcolor = code  
          };         
 </script>         
 </HEAD>        
 <BODY>
<form action="">
<input type="button" value="Red" onClick="document.bgColor = '#FF0000';">
<input type="button" value="White" onClick="document.bgColor = '#FFFFFF';">
<input type="button" value="Blue" onClick="document.bgColor = '#0000FF';">
<input type="button" value="Green" onClick="document.bgColor = '#008000';">
<input type="button" value="USA" onClick="document.bgColor = '#99CCFF';">
<input type="button" value="Off" onClick="document.bgColor = '#000000';">
<input type="button" value="Auto" onClick="document.bgColor = '#FFF888';">  
</form>
</BODY>
</HTML>

I am a super noob at this. I have created the following with a bunch of buttons. Two of the buttons are Auto and USA. I want the auto button to flash every color (i.e. red, white, blue, green,black, and any other colors i decide to add as buttons) onClick. I want the USA button to flash only red, white, and blue only, onClick. Also, although there is no CSS in the following I also want to position the buttons where I want them. I tried several things on this site suggesting positioning (i.e.float, absolute, relative) but do not know how to write the CSS for that (does it fall between style tags?). Any and all help would be appreciated.

`<HTML>

   <HEAD>
 <script type = “JavaScript” > 
           function changecolor (code)
            {           
 document.bgcolor = code  
          };         
 </script>         
 </HEAD>        
 <BODY>
<form action="">
<input type="button" value="Red" onClick="document.bgColor = '#FF0000';">
<input type="button" value="White" onClick="document.bgColor = '#FFFFFF';">
<input type="button" value="Blue" onClick="document.bgColor = '#0000FF';">
<input type="button" value="Green" onClick="document.bgColor = '#008000';">
<input type="button" value="USA" onClick="document.bgColor = '#99CCFF';">
<input type="button" value="Off" onClick="document.bgColor = '#000000';">
<input type="button" value="Auto" onClick="document.bgColor = '#FFF888';">  
</form>
</BODY>
</HTML>
Share Improve this question asked Aug 14, 2014 at 17:33 FistFist 211 silver badge6 bronze badges 1
  • If any of the answers below helped you, please select the best response to mark as the answer. – richbai90 Commented Aug 19, 2014 at 14:27
Add a ment  | 

5 Answers 5

Reset to default 2

Very simple, you can create a toggleColors function to change the colors each x time.

JavaScript:

// Globar vars
var timer;
var miliseconds = 500;

/**
* Function to toggle bgColor
* @param array colors Array of colors to set
**/
function toggleColors( colors ){
    clearTimeout(timer);
    var counter = 0
    var change = function(){
        document.bgColor = colors[ counter%colors.length ];// Change the color
        counter ++;
        if( colors.length > 1 )
            timer = setTimeout(change, miliseconds); // Call the changer
    };

    change();
}

HTML:

<input type="button" value="Red" onClick="toggleColors(['#F00'])">
<input type="button" value="White" onClick="toggleColors(['#FFF'])">
<input type="button" value="Blue" onClick="toggleColors(['#00F'])">
<input type="button" value="Green" onClick="toggleColors( ['#008000'])">
<input type="button" value="USA" onClick="toggleColors( ['#F00', '#FFF', '#00F'])">
<input type="button" value="Off" onClick="toggleColors( ['#000'])">
<input type="button" value="Auto" onClick="toggleColors( ['#F00', '#FFF', '#00F', '#0F0' ])">

You can see how works in http://jsfiddle/91ahbkem/1/.

UPDATED: I have made a CodePen to use in head tag: http://codepen.io/anon/pen/LpbDE

<script>
    function changecolor(color) {
        document.body.style.background = color
    }
</script>

<input type="button" value="Red" onClick="changecolor('#FF0000')" />

Or straight js

<input type="button" id="redbutton" value="red" />

<script>
    function changecolor(color) {
        document.body.style.background = color
    }

    document.getElementById('redbutton').onclick = changecolor('#FF0000');

</script>

If you go the straight js route, make sure that you place the script at the bottom of the body tag, after all the inputs. This makes sure that the DOM is successfully loaded before executing the script, there are other better ways of acplishing the same thing, but if you're just trying to learn then I'd remend putting the script tags at the bottom of the body just as a good practice.

Example http://jsfiddle/bex1gr7L/

This will get the color right from the value, instead of putting it on each html. and same with @rich, make sure the script run at the end of body

http://jsfiddle/b0e4gb4h/1/

<input type="button" value="black" onclick="changeColor(this)"/>

function changeColor(x) {
    color = x.value;
    document.body.style.background = color;
}

You should get in the habit from the beginning to NOT put javascript and CSS inline. As your pages get more plex, you will find this is a better way to go.

There are many ways to implement what you are describing. This way uses data attributes to store the color values and requestAnimationFrame to cycle the colors for Auto and USA.

http://jsfiddle/michaelburtonray/yqxbfyvc/

HTML

<form id="color-form">
    <input type="button" value="Red" data-color="red">
    <input type="button" value="White" data-color="white">
    <input type="button" value="Blue" data-color="blue">
    <input type="button" value="Green" data-color="#008000'">
    <input type="button" value="USA" data-color="red,white,blue">
    <input type="button" value="Off" data-color="black">
    <input type="button" value="Auto" data-color="red, white, blue, orange, black">
</form>

JS

(function(){

    var color_form, colors_array, animation_frame_request;

    function init() {
        var color_form = document.querySelector('#color-form');

        color_form.addEventListener('click', changeBackground, true);

    }


    function changeBackground(event) {
        event.preventDefault();

        // Stop the loop
        cancelAnimationFrame(animation_frame_request);

        console.log(event.target.dataset.color.split(',').length);

        var colors = event.target.dataset.color.split(',');

        if(colors.length > 1) {
            colors_array = colors;
            cycle_background_colors();
        } else {
            document.bgColor = colors[0];
        }


    }

    function cycle_background_colors() {
        animation_frame_request = requestAnimationFrame(cycle_background_colors);

        var color = colors_array.shift();
        console.log(typeof color, color);
        document.bgColor = color;
        colors_array.push(color);
    }

    document.addEventListener('DOMContentLoaded', init);    

}).call();

This will help with the USA and Off Button and will give you an idea on the Auto.

var nIntervId;

 function changeColor() {
     nIntervId = setInterval(flashUSA, 500);
 }

 function flashUSA() {
     var oElem = document.body;
     switch (oElem.style.backgroundColor) {
         case 'red':
             oElem.style.backgroundColor = 'blue';
             break;
         case 'blue':
             oElem.style.backgroundColor = 'white';
             break;
         case 'white':
             oElem.style.backgroundColor = 'red';
             break;
         default:
             oElem.style.backgroundColor = 'red';
             break;
     }
 }

 function stopChangeColor() {
     clearInterval(nIntervId);
 }

On the HTML you need to call the function on the "onClick" attrbute of the input-button element.

<input type="button" value="USA" onClick="changeColor();">  
<input type="button" value="Off" onClick="stopChangeColor();"> 
发布评论

评论列表(0)

  1. 暂无评论