通过单击按钮更改背景和文本颜色

时间:2018-09-05 20:07:35

标签: javascript css dom

我想实现一个按钮,该按钮可立即更改背景颜色和文本颜色。颜色是在数组中预定义的。

代码段

<?php

include 'src/wordlist.php';
include 'src/colorcodes.php';

$result1 = $one[array_rand($one)] . " " . $two[array_rand($two)];

$colormix1 = $colors[array_rand($colors)];
$colormix2 = $colors[array_rand($colors)];

if ($colormix1 == $colormix2) {
    $colormix2 = $colors[array_rand($colors)];
}

?>

<!DOCTYPE html>
<html>
<head>
</head>

<body style="background: <?php echo $colormix2; ?>;">
    <div class="table_1">
        <table>
            <tr>
                <th>
                    HEADER
                </th>
            </tr>
            <tr>
                <td>
                    <p style="color: <?php echo $colormix1; ?>;">&#187; <?php echo $result1; ?>. &#171;</p>
                </td>
            </tr>

        </table>
        </div>
     </body>
</html>

如何仅使用JavaScript来实现?

谢谢!

//编辑:

我找到了解决方法:

function changeBackground() {
    var colormix1 = colorcodes[Math.floor(Math.random() * colorcodes.length)];
    var colormix2 = colorcodes[Math.floor(Math.random() * colorcodes.length)];

    if (colormix1 == colormix2) {
    var colormix2 = colorcodes[Math.floor(Math.random() * colorcodes.length)];  
    }
    document.getElementById("quote").style.color = colormix1;
    document.getElementById("footer").style.background = colormix1;
    document.getElementById("ft-button").style.backgroundColor = colormix1;
    document.getElementById("ft-button").style.color = colormix2;
    document.getElementById("background").style.background = colormix2;
    }
</script>

通过按其ID调用元素,效果很好。

1 个答案:

答案 0 :(得分:1)

在JS中实现此目标非常简单。请参阅DOM API了解更多详情

运行此代码段进行演示

function changeBackground(value) {
  var bgElement = document.getElementsByClassName('background')[0];
  var textElement = document.getElementsByClassName('text')[0];

  if (bgElement) {
    bgElement.style.background = value;
  }

  if (textElement) {
    textElement.style.color = value;
  }
}
.background {
  width: 100vw;
  height: 100vh;
  background: #000;
}

.dropdown {
  width: 150px;
  height: 32px;
  margin: 16px;
}

.text {
  font-size: 16px;
  color: #000;
  margin: 16px;
}
<div class="text">
  This is some text
</div>
<div class="background">
  <select class="dropdown" onchange="changeBackground(value)">
    <option value="#F44336">Red</option>
    <option value="#E91E63">Pink</option>
    <option value="#9C27B0">Purple</option>
    <option value="#673AB7">Deep purple</option>
    <option value="#3F51B5">Indigo</option>
    <option value="#FFFFFF">White</option>
    <option value="#000000">Black</option>
  </select>
</div>