[英]How to set a div percentage width with a fixed position based on the parent element
I'm working on Wordpress and I need to make a div fixed on the top when the page is scrolled. 我正在使用Wordpress,我需要在页面滚动时将div固定在顶部。 The div ( .details ) must have a percentage width for responsive reasons.
由于响应原因,div( .details )必须具有百分比宽度。 I found a javascript to stop the div ( .details ) when it is 40px from the top, switching it from a relative position to a fixed one.
我找到了一个javascript来停止div( .details ),当它从顶部40px,从相对位置切换到固定的位置。 It has a 25% width when in relative position, but when it become fixed, the 25% width is now based on the window and it isn't based on the parent element ( .entry ), that is smaller than the window, so it become larger when I scroll.
它在相对位置时具有25%的宽度,但是当它变得固定时,25%的宽度现在基于窗口并且它不基于父元素( .entry ),即小于窗口,所以滚动时它会变大。 These are the CSS and the Javascript ( .carousel is the other div inside .entry , it's on the left of .details):
这些都是CSS和JavaScript(.carousel里面.entry的其他分区,这是对.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>
I need to make the width of .details div based on .entry and not on the window. 我需要根据.entry创建.details div的宽度,而不是在窗口上。 Anyone can find mistakes or need something else?
任何人都可以找到错误或需要别的东西吗? I'm not a pro in Javascript.
我不是Javascript的专家。 Thank you all!
谢谢你们!
The only way to do this is by setting the .details
width with JavaScript. 唯一的方法是使用JavaScript设置
.details
宽度。 Try this: 尝试这个:
$(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 )
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.