设置了position:fixed的元素没有宽高后,定位就失效了

问题我写在代码里的

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<style>
    *{
        margin: 0;
        padding: 0;
    }
    .content{
        width: 1000px;
        margin: 0 auto;
        background: #cccccc;
        height: 1000px;
        position: relative;
    }
    #box{
        position: fixed;
        left: 0;
        bottom: 50px;
    }
    .mask{
        width: 60px;
        height: 60px;
        background: #29262c;
        border-radius: 0 5px 5px 0;
    }
    .mask i {
        display: inline-block;
        background: url("img/play.png") no-repeat;
        width: 32px;
        height: 35px;
        position: absolute;
        top: 10px;
        left: 10px;
        cursor: pointer;
    }
    .mask:hover i{
        background-position: -32px 0;
    }
    .item{
        width: 0px;
        height: 60px;
        background-color: #29262c;
        opacity: 0.5;
        position: absolute;
        top: 0;
        left: 0;

    }
    .arrow{
        width: 25px;
        height: 58px;
        margin: 1px 0;
        line-height: 60px;
        background: #29262c;
        border-radius: 0 5px 5px 0;
        position: absolute;
        left: 61px;
        top: 0;
        color: #fff;
        font-weight: 900;
        cursor: pointer;
        text-align: center;
        display: none;
    }
</style>
<body>
<div class="content"></div>
<div id="box">
    <div class="mask">
        <i class="play"></i>
    </div>
    <div class="item"></div>
    <div class="arrow">&gt;</div>
</div>
<script src="http://libs.baidu.com/jquery/1.11.1/jquery.min.js"></script>
<script>
    //鼠标移入移出,箭头的出现与隐藏
    $('#box').hover(function () {
        $('.arrow').fadeIn();
    },function () {
        $('.arrow').hide();
    });

    if($('.item').width() == 0){      //点击>时,展开
        $('.arrow').on('click',function () {
            $('.item').animate({width : 500});
            $('.mask').hide('fast'); 
             //加个$('.mask').hide('fast')后,item就不在原来的位置了,
            $('.arrow').animate({left: 501 }).show(800);
            $('.arrow').html('&gt;');
        })
    }else{   //点击<时,收缩
        $('.arrow').on('click',function () {
            $('.item').animate({width : 0});
            $('.arrow').animate({left: 501}).show(800);
            $('.mask').show();

        })
    }







</script>
</body>
</html>
阅读 8.3k
2 个回答

因为你的fixed元素内部文档流中元素隐藏(display:none)之后,其高度变为0,其后代的position:absolute元素定位原点是为其左上角,则相当于是下移了60px。

补充
https://jsfiddle.net/44k88tgu/

是你.mask隐藏导致#box没有高度造成的,解决办法给#box加个 height: 50px;
隐藏前#box隐藏后#box

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题