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

问题描述 投票:0回答:1

我想实现一个按钮,它可以立即改变背景颜色和文字颜色。颜色在数组中预定义。

代码片段

<?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调用元素它工作得很好。

javascript css dom
1个回答
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>
© www.soinside.com 2019 - 2024. All rights reserved.