如何根据我单击的按钮更改div的颜色? (仅javascript / css / html无库)

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

我正在尝试创建祝酒通知。我有3个按钮按钮,我想根据我单击的按钮来更改烤面包的颜色。注意:您在框中输入的文字是在烤面包中显示的文字。

现在所有的颜色都用相同的颜色堆叠。

这里有代码(CSS不好,我只是在尝试东西)。

NOTE:我不能使用任何库,纯javascript / html / css没有jquery

有人可以帮忙吗?非常感谢!

HTML

<!DOCTYPE html>
<html>

</html>
<head>
    <meta charset="utf-8" />
    <title>Toast Notification</title>
    <link rel="stylesheet" href="style.css"/>
</head>
<body>

    <input type="text" placeholder="Grille pain" id="myInput">

    <button type="button" value="Error" onclick="toast()">Error</button>

    <button type="button" value="Success"onclick="toast()">Success</button>

    <button type="button" value="Info"onclick="toast()">info</button>

    <div id="toastcontainer">

    </div>
    <script src="toast.js"></script>
</body>

JAVASCRIPT

function toast(){
    const inputVal = document.getElementById("myInput").value;

    const container = document.getElementById("toastcontainer");

    const toastdiv = document.createElement("div");
    toastdiv.innerHTML = inputVal;
    container.appendChild(toastdiv);

}

CSS

#toastcontainer{
  width: 35%;
  position: absolute;
  bottom: 2%;
  left: 2%;
  border-color: #333333;
  background-color: blue;
}
java html css toast
2个回答
2
投票

您可以将'status'参数传递给函数,并根据状态确定要使用的颜色,如下所示:

function toast(status){
    const inputVal = document.getElementById("myInput").value;

    const container = document.getElementById("toastcontainer");

    const toastdiv = document.createElement("div");

    const toastColor = (status == 'error' ? 'red' : (status == 'success' ? 'green' : (status == 'info' ? 'blue' : '')));

    toastdiv.style.backgroundColor = toastColor;

    toastdiv.innerHTML = inputVal;
    container.appendChild(toastdiv);
}

然后将其传入您的HTML中:

<button type="button" value="Error" onclick="toast('error')">Error</button>

<button type="button" value="Success"onclick="toast('success')">Success</button>

<button type="button" value="Info"onclick="toast('info')">info</button>

0
投票

这里很简单\

document.getElementById( 'button1' ).addEventListener('click', function (event) {
console.log('green')
color('green', 'color')
}, false);
document.getElementById( 'button2' ).addEventListener('click', function (event) {
console.log('gold')
color('gold', 'color')
}, false);
document.getElementById( 'button3' ).addEventListener('click', function (event) {
console.log('blue')
color('blue', 'color')
}, false);
function color(color, id){
document.getElementById(id).style.backgroundColor=color;
}
#color{
width:150px;
height:50px;
background-color:black;
}
<div id ='color'></div>
<button id ='button1'>Green</button>
<button id ='button2'>gold</button>
<button Id="button3">blue </button>
© www.soinside.com 2019 - 2024. All rights reserved.