如何根据父元素使用固定位置设置 div 百分比宽度



我正在Wordpress上工作,我需要在页面滚动时在顶部固定一个div。出于响应原因,div (.details) 必须具有百分比宽度。我找到了一个 javascript 来停止div (.details) 当它距离顶部 40px 时,将其从相对位置切换到固定位置。它在相对位置时有 25% 的宽度,但是当它变得固定时,25% 的宽度现在基于窗口,而不是基于父元素 (.entry),它比窗口小,所以当我滚动时它会变大。这些是CSS和Javascript(.carousel是.entry中的另一个div,它位于.details的左侧):

<style>
.entry { position:relative; width:100%; }
.carousel { width:70%; height: auto; position: relative; float: left; margin-top: 0px;}
.details { width: 25px; height: 100%; float: right; margin-top: 0px; line-height: 20px;} 
</style>
<script>
$(window).scroll(function(){
if  ($(window).scrollTop() >= 90){
     $('.details').css({position:'fixed',right:40,top:40,width:'25%'});
} else {
     $('.details').css({position:'relative',right:0,top:0,width:'25%'});
    }
});
</script>

我需要根据 .entry 而不是窗口来制作 .detailsdiv 的宽度。任何人都可以发现错误或需要其他东西吗?我不是Javascript的专业人士。谢谢大家!

唯一的方法是使用 JavaScript 设置.details宽度。试试这个:

$(window).scroll(function(){
    if($(window).scrollTop() >= 90){
        $('.details').css({position:'fixed',right:40,top:40});
    } else {
        $('.details').css({position:'relative',right:0,top:0});
    }
});

// set the width of the details div when window resizes
window.addEventListener('resize', function(){
    var $el = $('.details')
    $el.width( $el.parent().outerWidth() * .25 )
})

这是一个粗略的例子

最新更新