Для постепенного исчезновения цветного прямоугольника выполните следующие 2 шага:
- Использование Свойство перехода CSS (позволяет плавно изменять значения свойств CSS в течение указанной продолжительности).
- Используйте JavaScript ( element .style.display = "none" ) для удаления затухающего элемента из потока документов.
// Get all elements with class="close"
let close = document.querySelectorAll(".close");
for (let i = 0; i < close.length; i++) {
close[i].onclick = function() {
// Get the parent of <span class="close"> (<div class="alert">)
let div = this.parentElement;
// Set the opacity of div to 0
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);
}
}
* {box-sizing: border-box;}
/* Style Alert Message */
.alert {
position: relative;
padding: 1rem 1.9rem 1rem 1rem;
margin-bottom: 1rem;
font-size: 1rem;
font-family: sans-serif;
border: 1px solid transparent;
border-radius: .25rem;
transition: opacity .6s linear;
}
/* Contextual Classes for alert */
.alert-primary {
color: #004085;
background-color: #cce5ff;
border-color: #b8daff;
}
.alert-secondary {
color: #383d41;
background-color: #e2e3e5;
border-color: #d6d8db;
}
.alert-warning {
color: #856404;
background-color: #fff3cd;
border-color: #ffeeba;
}
.alert-danger {
color: #721c24;
background-color: #f8d7da;
border-color: #f5c6cb;
}
/* Style Close Button */
.close {
position: absolute;
top: 0;
right: 0;
padding: 1rem;
color: inherit;
cursor: pointer;
font-size: inherit;
font-weight: 900;
background-color: transparent;
border: 0;
}
<p>Click on the × icon to fadeout the box:</p>
<div class="alert alert-primary">
<b>Primary!</b> This alert box indicates an important action.
<button type="button" class="close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="alert alert-warning">
<b>Warning!</b> This alert box could indicate a warning that might need attention.
<button type="button" class="close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="alert alert-danger">
<b>Danger!</b> This alert box could indicate a dangerous or potentially negative action.
<button type="button" class="close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="alert alert-secondary">
<b>Secondary!</b> This alert box indicates a less important action.
<button type="button" class="close">
<span aria-hidden="true">×</span>
</button>
</div>