微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript-如何基于父元素设置具有固定位置的div百分比宽度

我正在使用wordpress,滚动页面时需要在顶部固定一个div.出于响应原因,div(.details)必须具有百分比宽度.我发现了一个JavaScript,可在距顶部40px时停止div(.details),并将其从相对位置切换到固定位置.当处于相对位置时,它的宽度为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而不是基于窗口使.details div的宽度.
任何人都能发现错误或需要其他东西吗?我不是Java专业人士.
谢谢你们!

解决方法:

唯一的方法是通过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 )

})

这是一个crude example

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐