问题
I am trying to fade out Django success messages using a small Javascript script but cannot seem to get it to work. This is in my base.html
:
{% if messages %}
{% for message in messages %}
<div class="alert alert-{{ message.tags }}">
{{ message }}
</div>
{% endfor %}
{% endif %}
<script>
var m = document.getElementsByClassName("alert");
setTimeout(function(){
m.style.display = "none";
}, 3000);
</script>
回答1:
Django is only rendering your template, and return from a server side a HTML file which then need to be handled by your browser using CSS and javascript. An easy way to perform animation is using CSS transitions.
CSS Transitions
<div class="alert alert-{{ message.tags }}">
{{ message }}
</div>
.alert {
positition: relative;
opacity: 1;
visibility: visible;
transform: translateX(0px);
transition: visibility 0s, opacity 250ms, transform 250ms;
}
.alert.hide {
positition: relative;
opacity: 0;
visibility: hidden;
transform: translateX(-10px); // translateX, translateY, translateZ works well
transition: visibility 0s 250ms, opacity 250ms, transform 250ms;
}
Then use Javascript to add a class to it:
<script>
var m = document.getElementsByClassName("alert"); // Return an array
setTimeout(function(){
if (m && m.length) {
m[0].classList.add('hide');
}
}, 3000);
</script>
CSS animation library
This is the verbose version which consist of writting your own animation and configure exactly as you need, but a simple solution could be to use a CSS animation library like animate.css which provide a set of amazing transitions on the same principle.
Just be careful not using too much of them, you do not want your application to look like a christmas tree 🤣.
来源:https://stackoverflow.com/questions/58617996/how-to-fade-out-django-success-messages-using-javascript-or-css