我正面临一个问题,我需要在div位置固定和溢出y中使用scrollTop。 我确实看到了一个帖子 Using scrollTop inside of a fixed element with overflow-y:scroll
我遇到的问题是,我必须滚动的错误元素位于相对定位的内容中。所以这段代码不起作用
我的小提琴 http://jsfiddle.net/5446a6ds/2/
如果我删除具有相对位置的父级,它可以工作,但我不能这样做。 此外,错误可能位于相对定位的内容中的任何位置。因此,滚动到内容也不是一种选择。
HTML
<div id="relativeDad">
<div id="containerParent">
<div id="containerChild">
<section id="content">
this is a form<br>
this is a form<br>
this is a form<br>
this is a form<br>
this is a form<br>
this is a form<br>
this is a form<br>
this is a form<br>
this is a form<br>
this is a form<br>
this is a form<br>
this is a form<br>
this is a form<br>
this is a form<br>
<p class="form-error-msg">
Please provide missing information in the fields highlighted below.</p>
this is a form<br>
this is a form<br>
this is a form<br>
this is a form<br>
this is a form<br>
this is a form<br>
this is a form<br>
this is a form<br>
this is a form<br>
this is a form<br>
this is a form<br>
this is a form<br>
this is a form<br>
this is a form<br>
this is a form<br>
this is a form<br>
this is a form<br>
this is a form<br>
this is a form<br>
this is a form<br>
this is a form<br>
this is a form<br>
this is a form<br>
<fieldset>
<input type="date" id="dateOfBirth" required="">
<input type="password">
</fieldset>
<button id="button1">button</button>
</section>
</div>
</div>
</div>
Javascript
$("#button1").on("click", function(){
var position = $(".form-error-msg").position().top + $("#containerChild").scrollTop();
$("#containerChild").animate({scrollTop: position});
});
CSS
#relativeDad {
position: relative;
overflow: hidden;
}
#containerParent {
position: fixed;
background-color:blue;
height: 100%;
border:1px solid red;
width: 100%;
}
#containerChild {
position: fixed;
overflow-y: scroll;
height: 100%;
}
#content {
position:relative;
}
答案 0 :(得分:0)
你为位置添加了太多东西。具有
var position = $(".form-error-msg").position().top;
就足够了。因为.position是相对于偏移父项的,所以你只能在#containerChild中滚动
这是一个更新的小提琴。我之前添加了一个段落,并将高度更改为80%以演示相对计算。