如何制作多个按钮来更改不同的div背景颜色?

时间:2017-04-18 16:08:04

标签: javascript html css dom

看看我想要做的事情: https://codepen.io/SomeRandomGuy0/pen/aWvGxO

我可以使用“蓝色”按钮制作方形变色的颜色。我想要做的是制作多个按钮,将方块的颜色更改为按钮中的颜色。例如,如果我点击一个显示“绿色”的按钮,方块将变为绿色,如果我点击另一个显示“紫色”的按钮,它将变为紫色。

我正在使用JavaScript介绍DOM,很抱歉这个基本问题。

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';
}

5 个答案:

答案 0 :(得分:4)

您可以在按钮

的调用功能上将颜色作为参数传递

检查此代码笔

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;  
    }

答案 1 :(得分:3)

最简单的方法可能是更新changeColor()以获取color的参数。 例如,

使用Javascript:

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

然后在HTML中我们可以做到:

<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>

这将允许我们概括changeColor()函数,并使其更适用于将来的应用程序!

答案 2 :(得分:0)

在你的函数中使用if / else语句,我不打算为你做,但逻辑应该是,如果单击蓝色按钮,则更改为蓝色,如果单击红色按钮,则更改为红色等等。

答案 3 :(得分:0)

数据属性非常适用于此:https://jsfiddle.net/sheriffderek/0hm9wnk7/我还想使用rel将js挂钩到标记而不是类,以使事情保持清晰。

<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 comes 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
});

答案 4 :(得分:0)

编辑 - 这种方法是最简单的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 - 与css vars一起玩的借口

这是一种方法:

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>