How to fade out Django success messages using Javascript or CSS?

删除回忆录丶 提交于 2021-01-28 19:28:58

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!