使用显示属性淡入淡出

时间:2015-06-12 06:46:40

标签: javascript jquery html css

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>

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

2 个答案:

答案 0 :(得分:5)

使用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/

答案 1 :(得分:1)

你可以用css3来做,不需要jquery,而不是display none使用opacity 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>