簡體   English   中英

如何根據我單擊的按鈕更改 div 的顏色? ( javascript/css/html 只有沒有庫)

[英]How to change the color of the div depending on which button i click ? ( javascript/css/html ONLY no library)

我正在嘗試創建一個 Toast 通知。 我有 3 個不同的按鈕,我想根據我單擊的按鈕更改吐司的顏色。 注意:您在框中輸入的文本是出現在 toast 中的文本。

現在它都用相同的顏色堆疊起來。

這是代碼(CSS 不好,我只是在嘗試一些東西)。

注意:我不能使用任何庫,純 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>

爪哇腳本

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

您可以將“狀態”參數傳遞給您的函數,並根據狀態確定要使用的顏色,如下所示:

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>

簡單在這里\\

 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM