2015-04-22 64 views
0

我面临一个问题,我需要使用scrollTop里面的div位置固定和溢出y。 我没有看到一个帖子 Using scrollTop inside of a fixed element with overflow-y:scrollscrollTop里面的位置固定

我的问题是,错误元素我有一个滚动定位内容是相对位于内侧。所以这个代码不起作用

我的小提琴 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

你添加太多的位置。有

var position = $(".form-error-msg").position().top; 

是足够的,因为.POSITION是相对于已经偏移父所以你只能在#containerChild

滚动这里是一个更新的小提琴。我之前添加了一段,并将高度更改为80%以演示相对计算。

http://jsfiddle.net/5446a6ds/3/

+0

非常感谢。这是行得通的,但是当我在两者之间添加内容时,http://jsfiddle.net/5446a6ds/4/它在错误消息 – keerti

+0

@keerti之上的某处滚动有两个问题。首先,.position通过位置检测元素相对于其最接近的父元素的位置:relative set:必须从#content中移除position:relative。所以现在它会计算.form-error-msg相对于#relativeParent的位置。但是因为你有一个在#relativeParent之外的段落,它不会被考虑在内。一切都应该坐在最直接的容器内。例如:http://jsfiddle.net/5446a6ds/5/ – jerrylow

+0

谢谢这确实有帮助。谢谢 – keerti