【问题标题】:How to change background of div using button如何使用按钮更改div的背景
【发布时间】:2021-08-17 14:09:34
【问题描述】:

我有代码:

<?php
$link = mysqli_connect("localhost", "name", "password", "database");
$query = mysqli_query($link, "SELECT name, city, subject FROM user");

while($result = mysqli_fetch_assoc($query)) {
    $output = '<div class="block" style="background: grey">
          <form method="post">
          <p>Name: '.$result['name'].'</p>
          <p>Subject: '.$result['subject'].'</p>
          <p>City: '.$result['city'].'</p>
          <input type="button" name="grey" value="grey">
          <input type="button" name="red" value="red">
          </form>
          </div>';

    echo $output;
}
?>

如何使用按钮&lt;input type="button" name="grey" value="grey"&gt;&lt;input type="button" name="red" value="red"&gt; 更改&lt;div class="block"&gt; 的背景颜色?我试图这样做,但没有任何帮助。谁知道? P.S.:没关系,用什么(PHP还是JS)。

【问题讨论】:

  • 请展示你的尝试。
  • 我根本不懂JS,但是我找到了一些这样的方法:var input = document.getElementById("my_input_id"); input.onclick = function () { document.getElementById("my_div").style.backgroundColor = "blue"; };
  • 对不起,如果我的问题很奇怪,但我真的不知道该怎么做,因为我根本不会使用 JS
  • 这能回答你的问题吗? javascript change background color on click
  • 在一定程度上有所帮助,但是我有很多div,所以我不知道该怎么做,因为我从未使用过JS

标签: javascript php html


【解决方案1】:

为此,您可以使用 javascript。我建议在单击按钮时更改 div 的类并在 css 中添加好的规则,或者只是更改元素的样式属性。但是 css 在这里是为了 taht 并且使用类和 css 来做到这一点更干净。您还必须为按钮添加一个 ID,例如 #red 或 #blue 以类为例:

const div = document.querySelector('.block');
const btnRed = document.querySelector('#red');
const btnBlue = document.querySelector('#blue');
    
// Get the click on the button
btnRed.addEventListener('click', () => {
    // Change classes
    div.classList.add('red');
    div.classList.remove('blue');
    // If you don't want to use classes, change the background property
    div.style.backgroundColor = "red";
})

蓝色按钮则相反

如果你有多个 div,我认为你可以这样做:

const div = document.querySelectorAll('.block');
const btnRed = document.querySelector('#red');
const btnBlue = document.querySelector('#blue');
    
// Get the click on the button
btnRed.addEventListener('click', () => {
div.forEach(item => {
    // Change classes
    item.classList.add('red');
    item.classList.remove('blue');
    // If you don't want to use classes, change the background property
    item.style.backgroundColor = "red";
})
})

【讨论】:

  • 它只适用于一个区块,但有很多。我该怎么做才能让它们都变色?但是,当然,非常感谢!
  • 您可以在 const div 中使用 document.querySelectorAll,执行 foreach 并更改类或背景颜色代码在我之前的答案中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多