Javascript - 粘性按钮取决于标题宽度

标签 javascript jquery html css

我正在尝试使用 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')

我所看到的:

enter image description here

这是一个 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/

相关文章:

javascript - 使用 css 使 google maps api 循环

html - 用户选择静止图像复制到剪贴板

javascript - 使用 `ref` 时无法绑定(bind) `v-for`

javascript - 错误请求进行 AJAX 调用时 : This. readyState 未定义

javascript - 如何检查单选按钮是否被点击?

javascript - jQuery - 隐藏/显示不显示 div 并显示错误

javascript - 在 Angular2 组件模板中添加 ld+json 脚本标签

php - 提交表单问题: TypeError: this.表单为空

在另一个 JS 完成后加载 Javascript CSS

html - Woocommerce 产品选项 - 突出显示所选选项