javascript - 背景 : cover header image with menu always at the bottom of the screen

标签 javascript jquery html css

我想创建一个带有全宽/全高背景图片的页眉。在页面加载或调整大小时,菜单必须始终位于最底部。滚动时,当菜单触及屏幕顶部时,菜单会粘在顶部。

是这样的:http://www.themarmalade.com/

这是我当时得到的:

html:

<div class="minhaClass">
    <div class="menu-bottom">menu</div>
</div>
<div class="content"></div>

CSS:

   div{
    width:100%;
    height:350px;
}
.minhaClass{
    background: url(http://placehold.it/550x350) no-repeat center center;
    position: relative;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
    /*height:100%;*/
}
.menu-bottom {
    position: absolute;
bottom: 0;
margin: 0 auto;
width: 100%;
height: 3rem;
line-height: 3rem;
background-color: #5454b9;
color: #fffdfa;
text-align: center;
}
.content {
    width: 100%;
    height: 800px;
    background: grey;
}
.sticky {
    position: fixed;
    bottom: inherit;
    top: 0;
}

js:

$(document).ready(function() {
var w = $(window);
w.on("scroll", function(){
    if(w.scrollTop() >= 305){
        $('.menu-bottom').addClass('sticky');
    }
    else {
        $('.menu-bottom').removeClass('sticky');
    }
});

});

fiddle :http://jsfiddle.net/6ejv9/80/

感谢您花时间提供帮助!

最佳答案

我不确定这是否是您的意思,但我认为您希望 minhaClass div 占据 100% 的视口(viewport)。

如果是这种情况,请添加这些:

html,body{
    height: 100%;
}

取消注释minhaClass中的高度

.minhaClass{
background: url(http://placehold.it/550x350) no-repeat center center;
position: relative;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
height:100%;

接下来是 jquery,我们需要获取视口(viewport)的高度,这可以使用 $( window ).height();

所以你更新的 jquery 将是

$(document).ready(function() {
var w = $(window);
var b = $( window ).height();
w.on("scroll", function(){
    if(w.scrollTop() >= b){
        $('.menu-bottom').addClass('sticky');
    }
    else {
        $('.menu-bottom').removeClass('sticky');
    }
});
});

你可以在这里做更多的改进,比如 var b 考虑到覆盖菜单的高度,这样你的菜单就不会变粘,直到你滚动过去修复它,你可以减去使用此 var b = $( window ).height() - $('.menu-bottom').height();

从 b 开始菜单 div 的高度

关于javascript - 背景 : cover header image with menu always at the bottom of the screen,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28865509/

相关文章:

jquery - 在 JQuery Mobile 中设置背景图片

java - 如何检测网页的字符集

html - css - 如果浏览器对齐 div 以占据全高

javascript - 参数未传递且导航器在 createStackNavigator 中不可用 - React Navigation

javascript - 未压缩的 SoundCloud SDK

javascript - 使用 jQuery .each() 时的全局变量与局部变量

php - 简单的类似 DatePicker 的日历

javascript - 为什么我不能使用 get_post 方法 php 从 post 表单中获取值

javascript - 如何自定义Opentip默认样式?

javascript - 10秒后关闭弹出窗口