繁体   English   中英

我需要在js中创建CSS类的多个实例

[英]I need to create multiple instances of my CSS class in js

我在CSS中有一个名为toast的基类,其中包括我的所有基本样式,并带有一个javascript函数,该函数传递了toast类型以根据用户输入创建以提供反馈。 此函数编辑我的吐司类,并添加了一些图标和文本,如下所示:

#toast {
        visibility: hidden;
        width: 200px;
        min-height: 40px;
        max-height: 100px;
        border-radius: 5px;
        //and a whole bunch more styling
        }

然后我的js:

function showToast(type) {
    var label = null;
    var iconElement = null;
    var i = document.getElementById("toast")

    switch (type) {
        case 'success':
            i.style.border = 'solid 1px #007700';
            label = "SUCCESS";
            iconElement = "icons/success.png";
            break;
           //and then a bunch more cases for my other types
    }

    document.getElementById("title").innerHTML = label;
    document.getElementById("icon").src = iconElement;
    i.style.visibility = 'visible';
}

当前,每次我调用函数创建新的吐司时,它都会替换旧的吐司,但是我想对其进行更新,以便它们可以堆叠并能够一次输出多个反馈。 如何创建CSS类的多个实例,以免每次调用构造函数时它们都不会被覆盖?

您可能会给每个元素都添加ID,祝酒。 因此,当您运行此行(缺少分号(;))时:

var i = document.getElementById("toast")

您只是一遍又一遍地获取具有吐司ID的第一个元素,并将其替换。

您可能想要做的就是为您的toast元素分配一个类。

它可能看起来像这样:

<div id="genericToast1" class="toast"></div>
<div id="successToast1" class="toast success"></div>
<div id="burntToast1" class="toast burnt"></div>

然后在CSS中,您可以使用类选择器来修改它们,如下所示:

.toast 
{
    visibility: hidden;
    width: 200px;
    min-height: 40px;
    max-height: 100px;
    border-radius: 5px;
    //and a whole bunch more styling
}

.toast.success
{
//More styling for this kind of toast...
}

.toast.burnt
{
//More styling...
}

不需要JS!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM