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

javascript - How can I make multiple buttons to change a different div background color? - Stack Overflow

programmeradmin1浏览0评论

Take a look at what I am trying to make:

I was able to make the color of the square change color using the button "Blue". What I want to do is make multiple buttons to change the color of the square to what it says in the button. For example if I clicked on a button that says "Green", the square will turn green and if I clicked on another button that says "Purple", it will turn purple.

I am getting introduced to DOM in JavaScript so sorry for such a basic question.

HTML:

<html>
  <head>
    <meta charset = "UTF-8" />
    <title>DOM Practice</title>
  </head>
  <body>
    <div id = 'square'></div>
    <button onClick = changeColor() >Blue</button>
  </body>
</html>

CSS:

#square{
  width: 100px;
  height: 100px;
  background-color: red;
}

JavaScript:

function changeColor(){
  var elem = document.getElementById( 'square' );
  elem.style.backgroundColor = 'blue';
}

Take a look at what I am trying to make: https://codepen.io/SomeRandomGuy0/pen/aWvGxO

I was able to make the color of the square change color using the button "Blue". What I want to do is make multiple buttons to change the color of the square to what it says in the button. For example if I clicked on a button that says "Green", the square will turn green and if I clicked on another button that says "Purple", it will turn purple.

I am getting introduced to DOM in JavaScript so sorry for such a basic question.

HTML:

<html>
  <head>
    <meta charset = "UTF-8" />
    <title>DOM Practice</title>
  </head>
  <body>
    <div id = 'square'></div>
    <button onClick = changeColor() >Blue</button>
  </body>
</html>

CSS:

#square{
  width: 100px;
  height: 100px;
  background-color: red;
}

JavaScript:

function changeColor(){
  var elem = document.getElementById( 'square' );
  elem.style.backgroundColor = 'blue';
}
Share Improve this question asked Apr 18, 2017 at 16:08 Miguel NunezMiguel Nunez 793 silver badges12 bronze badges 0
Add a ment  | 

5 Answers 5

Reset to default 4

You can pass the color as parameter on calling function at button

check this code pen

https://codepen.io/anon/pen/BRoPJo

    <button onClick = changeColor('Blue') >Blue</button>
    <button onClick = changeColor('green') >green</button>
    <button onClick = changeColor('yellow') >yellow</button>

JS

    function changeColor(color){
     var elem = document.getElementById( 'square' );
     elem.style.backgroundColor =color;  
    }

The simplest approach could be to update changeColor() to take an argument of color. So for example,

Javascript:

function changeColor(color){
  var elem = document.getElementById( 'square' );
  elem.style.backgroundColor = color;
}

Then in the HTML we could do:

<html>
  <head>
    <meta charset = "UTF-8" />
    <title>DOM Practice</title>
  </head>
  <body>
    <div id = 'square'></div>
    <button onClick = changeColor('blue') >Blue</button>
    <button onClick = changeColor('red') >Red</button>
  </body>
</html>

This will allow us to generalize the changeColor() function, and make it more reusable for future applications!

Use an if/else statement in your function, I'm not going to do it for you, but the logic should be, if blue button is clicked, change to blue, if red button is clicked change to red and so on.

data-attributes are great for this: https://jsfiddle/sheriffderek/0hm9wnk7/ I also like to use rel to hook the js into the markup instead of classes to keep things really clear.

<div class='square' rel='box'></div>

<ul class='color-list' rel='box-colors'>
 <li class='color' data-color='red'>red</li>
 <li class='color' data-color='blue'>blue</li>
 ...
</ul>

...

.square {
  width: 100px;
  height: 100px;
  background: lightgray;
}

.color-list .color {
  cursor: pointer;
}

...

// $('selector/element') - 'queries'(looks for) for the object in the DOM / j-'query' get it?
// var $thing (with $sign is just a convention to remind you that it's a jQuery object / that es with some jQuery specific stuff)
var $box = $('[rel="box"]'); // cache the element with rel='box' to a pointer(variable) for use later
var $boxColors = $('[rel="box-colors"]'); // same idea
var $colorTriggers = $boxColors.find('.color'); // same idea / see .find() method

$colorTriggers.on('click', function() { 
  // .on() is a method for attaching event handlers - in this case, 'click'
  thisColor = $(this).data('color'); // get the clicked element's data-attr for data-color
  $box.css('background', thisColor); // set the box css background to the color you just retrieved from the data-attr
});

EDIT -- this approach is simplest IMO

Codepen DEMO

HTML:

<html>
  <head>
    <meta charset = "UTF-8" />
    <title>DOM Practice</title>
  </head>
  <body >
    <div id='preview'></div>
    <input id="colorpicker" type="color" />
  </body>
</html>

JS:

document.addEventListener('DOMContentLoaded', e => {
  const preview = document.getElementById('preview');
  const picker = document.getElementById('colorpicker');
  preview.style.backgroundColor = picker.value;
  picker.addEventListener('input', e => {
    preview.style.backgroundColor = e.currentTarget.value
  })
})

ORIGINAL -- an excuse to play with css vars

Here's an approach:

const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];
const getRandomColor = () => colors[Math.floor(Math.random() * colors.length)]
const selectColor = (color) => document.body.style.setProperty('--current', color);

document.addEventListener('DOMContentLoaded', e => {
  
  const preview = document.getElementById('square');
  const changeColor = (e) => {
    let color = getComputedStyle(e.currentTarget).getPropertyValue('--color-name');
    
    selectColor(color);
    
    let logStyles = ` 
      color: black; 
      font-weight: bold; 
      background-color: ${color};
      font-size: 18px;`;
                        
    
    console.log(`color changed to %c ${color} `, logStyles);
  }

  // 1. select purple for starting color
  // 2. create buttons
  // NOTE: I created the buttons programatically, but you could just as easily
  // 
  //  <button style="--color-name:red;">red</button>
  //  <button style="--color-name:orange;">orange</button>
  //  etc...
  
  selectColor('rebeccapurple')
  colors.forEach((color, i) => {
    let button = document.createElement('button');
    button.style.setProperty('--color-name', color);
    button.onclick = changeColor;
    button.textContent = color;
    document.body.appendChild(button);
  })

})
body {
    --current: 'green';
  }
#square{
  background-color: var(--current);
  width: 150px;
  height: 150px;
  margin-bottom: 15px;
}
button {
  padding: 8px 16px;
  background: white;
  border: 1px solid #f3f3f3;
  color: var(--color-name);
  margin-right: 8px;
}
<html>
  <head>
    <meta charset = "UTF-8" />
    <title>DOM Practice</title>
  </head>
  <body >
    <div id = 'square'></div>

  </body>
</html>

发布评论

评论列表(0)

  1. 暂无评论