JSFiddle - React, Tailwind, and code Playground

by mmis1000

HTML

<div class="spoiler" title="招呼語">
    <div class="spoiler" title="早安語">早安,
        <br/>你好。</div>
    <div class="spoiler" title="午安語">午安,
        <br/>你好。</div>
    <div class="spoiler" title="晚安語">晚安,
        <br/>你好。</div>
</div>

CSS

.toggle {
    /*start of decorate code*/
    cursor:pointer;
    -webkit-border-radius: 6px;
    -moz-border-radius: 6px;
    border-radius: 6px;
    padding:2px;
    width:100%;
    border:1px;
    border-style:solid inset;
    margin:0px;
    margin-top:2px;
    margin-bottom:2px;
    /*end of decorate code*/
}
.showingButton {
    /*start of decorate code*/
    margin-bottom:0px;
    margin-top:2px;
    -webkit-border-top-left-radius: 6px;
    -webkit-border-top-right-radius: 6px;
    -moz-border-radius-topleft: 6px;
    -moz-border-radius-topright: 6px;
    border-top-left-radius: 6px;
    border-top-right-radius: 6px;
    -webkit-border-bottom-right-radius: 0px;
    -webkit-border-bottom-left-radius: 0px;
    -moz-border-radius-bottomright: 0px;
    -moz-border-radius-bottomleft: 0px;
    border-bottom-right-radius: 0px;
    border-bottom-left-radius: 0px;
    /*end of decorate code*/
}
.spoiler {
    /*need at least class to work*/
    /*start of decorate code*/
    -webkit-border-bottom-right-radius: 6px;
    -webkit-border-bottom-left-radius: 6px;
    -moz-border-radius-bottomright: 6px;
    -moz-border-radius-bottomleft: 6px;
    border-bottom-right-radius: 6px;
    border-bottom-left-radius: 6px;
    padding:4px;
    width:100%;
    border:1px;
    border-style:solid;
    margin:0px;
    margin-bottom:2px;
    /*end of decorate code*/
}
.hide {
    /*need at least class to work*/
    display:none;
}
.toggle, .spoiler, .hide {
    /*start of decorate code*/
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}
.toggle:after {
    /*start of decorate code*/
    content:"[Show]"
    /*end of decorate code*/
}
.showingButton:after {
    /*start of decorate code*/
    content:"[Hide]"
    /*end of decorate code*/
}

JavaScript

function getSpoilerBotton(element) {
    var target = $(element);
    //use cloure to bind object
    function tab() {
        if (!target.hasClass("hide")) {
            target.addClass("hide");
            $(this).removeClass("showingButton");
        } else {
            target.removeClass("hide");
            $(this).addClass("showingButton");
        }
    }
    //use title to prevent from unable display when js failed    
    var title = target.attr("title");
    target.removeAttr("title");
    title = (title !== undefined) ? title : "";
    var toggleButtom = $("<div></div>").addClass("toggle").click(tab).text(title);
    return toggleButtom;
}

function initSpoiler() {
    //only use on div
    $("div.spoiler").addClass("hide").each(function () {
        botton = getSpoilerBotton(this);
        $(this).before(botton);
    });
}

initSpoiler();