使用显示属性淡入和淡出

Fade in and out using display property

本文关键字:淡出 淡入 属性 显示      更新时间:2023-09-26

function myFunction() {
    document.getElementById("myDIV").style.display = "block";
    document.getElementById("second").style.display = "none";
}
function myFunction2() {
    document.getElementById("second").style.display ="block";
    document.getElementById("myDIV").style.display = "none";
}
#myDIV {
    width: 500px;
    height: 500px;
    background-color: lightblue;
    display: none;
}
    
#second {
    width: 500px;
    height: 500px;
    background-color: lightblue;
    display: none;
}
<button onclick="myFunction()">Try it</button>
<button onclick="myFunction2()">Try this now</button>
<div id="myDIV">
    This is my DIV element.
</div>
<div id="second">
    This is my DIV2 element.
</div>

上面的代码使两个分区在同一位置交替。我怎样才能以分裂出现和消失的方式操纵它们。更具体地说,淡入(出现)淡出(消失)。谢谢

jQuery用于事件处理和fade动画:

.HTML:

<button id="button1">Try it</button>
<button id="button2">Try this now</button>

Javascript:

$('#button1').on('click', function () {
    $('#second').fadeOut(2000, function () {
        $('#myDIV').fadeIn(2000);
    });
});

$('#button2').on('click', function () {
    $('#myDIV').fadeOut(2000, function () {
        $('#second').fadeIn(2000);
    });
});

演示:http://jsfiddle.net/tusharj/rLvpqcLb/

你可以用 css3 做,不需要 jquery,而不是显示 none 使用不透明度 0

<!DOCTYPE html>
<html>
<head>
    <style>
        #myDIV {
            width: 500px;
            height: 500px;
            background-color: lightblue;
            opacity: 0;
            transition: all 2s linear;
        }
        #second {
            width: 500px;
            height: 500px;
            background-color: lightblue;
            display: none;
        }
    </style>
</head>
<body>
    <button onclick="myFunction()">Try it</button>
    <button onclick="myFunction2()">Try this now</button>
    <div id="myDIV">
        This is my DIV element.
    </div>
    <div id="second">
        This is my DIV2 element.
    </div>
    <script>
    function myFunction() {
        document.getElementById("myDIV").style.opacity = "1";
        document.getElementById("second").style.display = "none";
    }
</script>