如何为div设置动画以使其淡入或滑入Click

时间:2018-09-21 20:04:33

标签: javascript css

    // Get the modal
    var modal = document.getElementById('myModal');

    // Get the button that opens the modal
    var btn = document.getElementById("myBtn");

    // Get the <span> element that closes the modal
    var span = document.getElementsByClassName("close")[0];

    // When the user clicks the button, open the modal 
    btn.onclick = function() {
        modal.style.display = "block";
    }

    // When the user clicks on <span> (x), close the modal
    span.onclick = function() {
        modal.style.display = "none";
    }

    // When the user clicks anywhere outside of the modal, close it
    window.onclick = function(event) {
        if (event.target == modal) {
            modal.style.display = "none";
        }
    }

我希望在不使用jquery的情况下将一些动画添加到div中,因为它是用于显示横幅的,并且我不想使用库来增加整体文件的大小。应该很简单,但似乎无法使其正常工作。

1 个答案:

答案 0 :(得分:0)

像这样更改代码:

// Get the modal
var modal = document.getElementById('myModal');

// Get the button that opens the modal
var btn = document.getElementById("myBtn");

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks the button, open the modal 
btn.onclick = function() {
    modal.style.cssText = "visibility: visible;opacity: 1;transition: 0.3s";
}

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
    modal.style.cssText = "visibility: hidden;opacity: 0;transition: 0.3s";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}

我将您的打开样式更改为:

modal.style.cssText = "visibility: visible;opacity: 1;transition: 0.3s";

关闭样式:

modal.style.cssText = "visibility: hidden;opacity: 0;transition: 0.3s";

工作示例:https://jsfiddle.net/sz8hq9vm/2/