Cómo - Alertas
Aprenda a crear mensajes de alerta con CSS.
Alertas
Los mensajes de alerta se pueden utilizar para notificar al usuario sobre algo especial: peligro, éxito, información o advertencia.
Crear un mensaje de alerta
Paso 1) Agregar HTML:
Ejemplo
<div class="alert">
<span class="closebtn"
onclick="this.parentElement.style.display='none';">×</span>
This is an alert box.
</div>
Si desea poder cerrar el mensaje de alerta, agregue un elemento <span> con un onclick
atributo que diga "cuando haga clic en mí, oculte mi elemento principal", que es el contenedor <div> (clase="alerta").
Sugerencia: use la entidad HTML " ×
" para crear la letra "x".
Paso 2) Agregar CSS:
Dale estilo al cuadro de alerta y al botón de cerrar:
Ejemplo
/* 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;
}
Muchas alertas
Si tiene muchos mensajes de alerta en una página, puede agregar el siguiente script para cerrar diferentes alertas sin usar el atributo onclick en cada elemento <span>.
Y, si desea que las alertas desaparezcan lentamente cuando haga clic en ellas, agregue opacity
y transition
a la alert
clase:
Ejemplo
<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>
Sugerencia: consulte también Notas .