How TO - アラート

❮ 前章へ 次章へ ❯

CSS を使用してアラート・メッセージの作成方法を学習します。


アラート

アラート・メッセージは、危険、成功、情報、警告などの何か特別なことをユーザに通知するために使用することができます。

× Danger! Indicates a dangerous or potentially negative action.
× Success! Indicates a successful or positive action.
× Info! Indicates a neutral informative change or action.
× Warning! Indicates a warning that might need attention.

アラート・メッセージの作成

ステップ 1) HTML の追加:

<div class="alert">
  <span class="closebtn" onclick="this.parentElement.style.display='none';">&times;</span>
  This is an alert box.
</div>

アラート・メッセージを閉じる機能が必要な場合は、「私をクリックすると、親要素(コンテナ <div> (class="alert"))を非表示にします」 という onclick イベント属性を持つ要素を追加します。

チップ: 文字 "x" を作成するには、HTML エンティティの "&times;" を使用します。


ステップ 2) CSS の追加:

アラート・ボックスと閉じるボタンをスタイルします:

/* The alert message box */
.alert {
    padding: 20px;
    background-color: #f44336; /* Red */
    color: white;
    margin-bottom: 15px;
}

/* The close button */
.closebtn {
    margin-left: 15px;
    color: white;
    font-weight: bold;
    float: right;
    font-size: 22px;
    line-height: 20px;
    cursor: pointer;
    transition: 0.3s;
}

/* When moving the mouse over the close button */
.closebtn:hover {
    color: black;
}
Try it Yourself »

多数のアラート

ページに多数のアラート・メッセージがある場合は、次のスクリプトを追加して、各 <span> 要素の onclick 属性を使用せずに、 いろいろなアラートを閉じることができます。

また、アラートをクリックした時にゆっくりフェードアウトさせたい場合は、alert クラスに opacitytransition を追加します:

<style>
.alert {
    opacity: 1;
    transition: opacity 0.6s; /* 600ms to fade out */
}
</style>

<script>
// Get all elements with class="closebtn"
var close = document.getElementsByClassName("closebtn");
var i;

// Loop through all close buttons
for (i = 0; i < close.length; i++) {
    // When someone clicks on a close button
    close[i].onclick = function(){

        // Get the parent of <span class="closebtn"> (<div class="alert">)
        var div = this.parentElement;

        // Set the opacity of div to 0 (transparent)
        div.style.opacity = "0";

        // Hide the div after 600ms (the same amount of milliseconds it takes to fade out)
        setTimeout(function(){ div.style.display = "none"; }, 600);
    }
}
</script>
Try it Yourself »

チップ: Notes もチェックしてください。


❮ 前章へ 次章へ ❯