gpt4 book ai didi

javascript - 如何根据父元素设置固定位置的div百分比宽度

转载 作者:行者123 更新时间:2023-11-29 10:44:38 25 4
gpt4 key购买 nike

我正在使用 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 的宽度。任何人都可以发现错误或需要其他东西吗?我不是 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 )

})

这是一个crude example

关于javascript - 如何根据父元素设置固定位置的div百分比宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22050159/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com