美文网首页H5开发
CSS 做一个舒适的遮罩层

CSS 做一个舒适的遮罩层

作者: 风之化身呀 | 来源:发表于2017-08-20 14:04 被阅读16次

如果你做的遮罩是通过hide()或show()来控制的,那么意味着你做的遮罩的opacity是突变的,而不是线性减少或增加,给用户的感觉就好像闪了一下,体验不佳。本文就是解决这个问题。
看下这个html结构

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no">
    <title>搜狐墨客</title>
    <style>
        .mask{
            position: fixed;
            top:0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: #ccc;
            transition:opacity 0.3s;
            opacity: 0;
            z-index: -1;
        }
        .opacity{
            opacity: 0.3;
        }
        .content{
            position: absolute;
            z-index: 2;
            width: 80%;
            height: 300px;
            background-color: green;
            bottom:-300px;
            transition:bottom 0.3s;
            left: 0;
            right: 0;
            margin: 0 auto;
        }
        .top{
            bottom:10px;
        }
        button{
            width: 100px;
            height: 100px;
        }
        header{
            height: 100px;
            background-color: red;
            position: fixed;
            top:0;
            width: 100%;
        }
        main{
            margin-top: 100px;
            height: 500px;
            background-color: #fff;
        }
        footer{
            height: 67px;
            background-color: green;
        }
    </style>
</head>
<body>
<div id="content">
    <header>header</header>
    <main>main
    <button class="label1">上去</button>
    <button class="label2">下来</button>
    </main>
    <footer>footer</footer>
</div>
<div class="mask">  
</div>
<div class="content">
    确定删除吗?
</div>
<script src="../static/js/thirdLib/zepto.min.js"></script>
<script>
    var $content=$('.content'),
    $mask=$('.mask'),
    $button1=$('.label1'),
    $button2=$('.label2');
    $button1.on('click', function(event) {
        console.log('q');  
        debugger;
        $mask.addClass('opacity').css('z-index', 1);;
        $content.addClass('top');
        /* Act on the event */
    });
    $mask.on('click', function(event) {
        $content.removeClass('top');
        $mask.removeClass('opacity');
        setTimeout(function(){
            $mask.css('z-index', -1);
        },300)
    });
</script>
</body>
</html>

实现原理就是动态改变mask的z-index值,动画开始时,提升mask的z-index使其遮住#content的内容并让其opacity顺利线性增加,结束动画时,要注意先让其opacity线性减少至0后再改变其z-index值使#content内容展现出来,这里使用了setTimeout来等待opacity完成动画。

相关文章

网友评论

    本文标题:CSS 做一个舒适的遮罩层

    本文链接:https://www.haomeiwen.com/subject/kcsfdxtx.html