2016-07-26 28 views
0

我创建了两个div,一个在顶部,一个在底部。 我创建了一个按钮。我在左下角页面给了一个固定位置的财产。 如果我滚动页面,按钮仅固定在该位置。 基本上按钮处于整个页面的固定位置。 我的要求: 当我滚动页面时,按钮应该只固定一定的高度。 当我滚动页面时,按钮应该只固定在左边按钮,直到第一个div底线触及按钮底线。 和文我滚动页面的按钮应该与第一个div的底线一起移动。只有一个div的固定位置的按钮

基本上按钮应该是固定的位置,直到第一个div底线。 当第一个div底线与按钮底线一起折叠时,该按钮应该是相对/绝对的并随之一起移动。

希望你明白我的要求。 下面是我的代码,我找的要求


 

 
    #top { 
 
    border: 1px solid black; 
 
    height: 900px; 
 
    width: 80%; 
 
    position: absolute; 
 
} 
 

 
.button { 
 
    background-color: #4CAF50; 
 
    border: none; 
 
    color: white; 
 
    bottom: 0px; 
 
    font-size: 16px; 
 
    margin-left: 0px; 
 
    cursor: pointer; 
 
    padding: 10px 24px; 
 
    position: fixed; 
 
} 
 

 
#bottom { 
 
    border: 1px solid black; 
 
    height: 900px; 
 
    width: 80%; 
 
    top: 910px; 
 
    position: relative; 
 
} 
 

 
#middle { 
 
    bottom: 50px; 
 
    position: fixed; 
 
}
<html> 
 

 
    <body> 
 
    <div id="top"> 
 
     <div id="middle"> 
 
     <button class="button">Fixed Element</button> 
 
     </div> 
 
    </div> 
 

 
    <br> 
 
    <br> 
 
    <div id="bottom"> 
 

 

 
    </div> 
 
    </body> 
 

 
</html>

+0

位置固定是相对于视,有这个quesiton一些有用的提示:HTTP: //stackoverflow.com/questions/5209814/can-i-position-an-element-fixed-relative-to-par你可能会觉得有用。 – connorb

回答

0

我觉得这是不可能的,只有css。您需要javascriptjquery。 你需要jquery来运行我的例子。你应该测量与top或其他元素的滚动量,并相应地改变按钮的底部/顶部是这样的:

jQuery的

$(window).scroll(function() { 
    if (($(this).scrollTop()+$(window).height())>$('#top').height()){ 
    $("#btn_fixed").css({ bottom: ($(this).scrollTop()+$(window).height()- $('#top').height())+"px" }); 
    }else{ 
    $("#btn_fixed").css({ bottom: '0px' }); 
    } 
}); 

我已经改变css和代码的html

CSS

#top { 
    border: 1px solid black; 
    height: 900px; 
    width: 80%; 
    position: absolute; 
} 

.button { 
    background-color: #4CAF50; 
    border: none; 
    color: white; 
    bottom: 0px; 
    font-size: 16px; 
    margin-left: 0px; 
    cursor: pointer; 
    padding: 10px 24px; 
    position: fixed; 
} 

#bottom { 
    border: 1px solid black; 
    height: 900px; 
    width: 80%; 
    top: 910px; 
    position: relative; 
} 

HTML

<div id="top"> 
    <div id="middle"> 
    <button class="button" id="btn_fixed">Fixed Element</button> 
    </div> 
</div> 

<br> 
<br> 
<div id="bottom"> 


</div> 

工作小提琴:https://jsfiddle.net/khairulhasanmd/h9y0bf1g/

+0

谢谢 你能解决这个使用“Javascript”?而不是Jquery 我会帮助我很多。 – Aryan

+0

在'javascript'中的实现需要更多的代码行,事件监听器e.t.c.你可以通过搜索谷歌自己来转换它。如果这有帮助,您可以将此答案标记为已接受。谢谢。 –