我正在尝试使用 ul
和一个 div
制作一个粘性 header 。
粘性标题工作正常,但我也想使 div
粘性,只有当屏幕宽度为 >= 981px
时。
代码
HTML:
<div id="sub-header-info">
<div class="wrap-perfil">
<nav class="barra-header">
<ul>
<li><a class="actividad" href="index.php">Actividad</a></li>
<li><a class="favoritos" href="#">Favoritos</a></li>
<li><a class="seguidores" href="seguidores.php">Seguidores</a></li>
<li><a class="seguidos" href="seguidos.php">Siguiendo</a></li>
</ul>
</nav>
</div>
</div>
<div class="wrap-perfil">
<div class="boton-seguir"><a href="#">Seguir</a></div>
</div>
CSS:
.boton-seguir {
float:right;
position: relative;
top: -40px;
}
.boton-fixed {
position: fixed;
top: 161;
right: 90px;
}
JavaScript:
var stickyOffset = $('#sub-header-info').offset().top;
$(window).scroll(function(){
var sticky = $('#sub-header-info'),
scroll = $(window).scrollTop();
if (scroll >= stickyOffset) sticky.addClass('fixed');
else sticky.removeClass('fixed');
});
var stickyOffset2 = $('.boton-seguir').offset().top;
var boton = $('.boton-seguir');
scroll = $(window).scrollTop();
if (screen.width >= 981 && scroll >= stickyOffset2)
boton.addClass('boton-fixed')
我所看到的:
这是一个 Live Demo 。
这里有什么问题?谁能帮帮我?
提前致谢。
最佳答案
首先,因为您的按钮不在粘性 div 内,所以您还必须使其具有粘性。像这样修改你的 JavaScript:
var stickyOffset = $('#sub-header-info').offset().top;
$(window).scroll(function(){
var sticky = $('#sub-header-info'),
scroll = $(window).scrollTop(),
stickyBtn = sticky.next();
if (scroll >= stickyOffset) {
sticky.addClass('fixed');
stickyBtn.addClass('fixedBtn');
}
else {
sticky.removeClass('fixed');
stickyBtn.removeClass('fixedBtn');
}
});
现在您可以像这样使用媒体查询来捕获该按钮:
@media only screen and (min-width: 981px) {
.wrap-perfil.fixedBtn {
position:fixed;
/* We need a z-index greater than #sub-header-info's */
z-index: 1000000;
/* Probably better to remove the negative-top off of the child element,
* but this hack will demonstrate how it works. :) */
top: 60px;
}
}
@media only screen and (max-width: 980px) {
.wrap-perfil.fixedBtn {
/* Add CSS for smaller screens here. */
}
}
关于Javascript - 粘性按钮取决于标题宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30363326/