Hello People 我需要的是获取任何部分的偏移量,然后使所有部分的位置都是绝对的: 所有部分返回偏移量为0px的问题
$(document).ready(function () {
$('section').each(function (index, element) {
var $this = $(this);
$this.css('top', $this.offset().top + 'px');
$this.css('position', 'absolute');
});
})
section {
width: 100%;
height: 400px;
background-color:#ff5b74;
}
.section-2{
height:500px;
background-color:#00ff6b;
}
.section-3{
background-color:#5066e9;
}
.section-4{
background-color:#ff6a00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<section class="section-1"></section>
<section class="section-2"></section>
<section class="section-3"></section>
<section class="section-4"></section>
最佳答案
问题在于,对于每个部分,您都设置了绝对位置,这使得它在更改其余部分之前脱离了流程。因此其余部分将忽略此部分占用的空间并填充它。
这就是为什么他们都占据同样的榜首位置
所有section的置顶位置设置完成后需要设置绝对位置,即在循环函数之外。
$(document).ready(function() {
$('section').each(function(index, element) {
var $this = $(this);
$this.css('top', $this.offset().top + 'px');
});
$('section').css('position', 'absolute');
})
section {
width: 100%;
height: 400px;
background-color: #ff5b74;
}
.section-2 {
height: 500px;
background-color: #00ff6b;
}
.section-3 {
background-color: #5066e9;
}
.section-4 {
background-color: #ff6a00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<section class="section-1"></section>
<section class="section-2"></section>
<section class="section-3"></section>
<section class="section-4"></section>
关于javascript - 获得偏移然后使位置绝对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43657244/