当 position:sticky 遇到 bootstrap 浮动布局时候的踩坑记录


本文摘自PHP中文网,作者青灯夜游,侵删。

当第一次接触到 position:sticky 这个属性,我就意识到之前的不少 js 场景可以用这个 css 属性去改写。譬如 网站 右侧的不少广告,滚动上去后需要 fixed,完全就是 sticky 的应用啊。

今天要说的是 文章详情页 右侧的目录栏,当页面下滑的时候,它也会固定到页面顶部,之前是用 js 去监听 scroll 事件,然后根据位置进行判断,toggle fixed 的方案,出于一些原因,决定对它用 sticky 去重写。

几下就写完了,去掉滚动事件监听,然后将菜单元素 .post-nav 加上 position:sticky; top:0 样式,但是,不起效!

wtf! 百思不得其解,我开始搜索原因。在 so 搜到了 这个,说到可能是元素的父级元素有对 overflow 属性进行处理,比如加了什么 overflow:hidden 啥的,但是看了下,并没有这种情况。

然后我猜想会不会是 bootstrap 布局的问题(事实上确实有关系),写下 demo:

<!DOCTYPE html>
<html>
<head>
  <title></title>
  <link href="//cdn.bootcss.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet">
  <style>
    body {font-size: 50px; font-weight: 900;}
    .main {height: 2000px; background: #eee}
    .menu {height: 200px; background: yellow}
    .ad {height: 200px; background: red; position: sticky; top: 0px;}
    .guess {height: 200px; background: blue;}
  </style>
</head>
<body>
<p class="container">
  <p class="row">
    <p class="col-md-8 main">content</p>
    <p class="col-md-4">
      <p class="menu">menu</p>
      <p class="ad">ad</p>
      <p class="guess">others</p>
    </p>
  </p>
</p>
</body>
</html>

但是没问题,突然想到网站用的 bootstrap 版本是 3.x,然后改成 3.3.7 的版本,这时候问题就出来了。

这时候问题就比较好定位了,4.x 用的是 flex 布局,而 3.x 还是 float 浮动布局,问题应该是出在这里了。

最终代码(参考 这个 issue):

<!DOCTYPE html>
<html>
<head>
  <title></title>
  <link href="//cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
  <style>
    body {font-size: 50px; font-weight: 900;}
    .main {height: 2000px; background: #eee}
    .side {height: 2000px;}
    .menu {height: 200px; background: yellow}
    .ad {height: 200px; background: red; position: sticky; top: 0px;}
    .guess {height: 200px; background: blue;}
  </style>
</head>
<body>
<p class="container">
  <p class="row">
    <p class="col-md-8 main">content</p>
    <p class="col-md-4 side">
      <p class="menu">menu</p>
      <p class="ad">ad</p>
      <p class="guess">others</p>
    </p>
  </p>
</p>
</body>
</html>

对应到开始的问题上,因为 menu 是属于 .col-md-3 元素的,所以右边的 .col-md-3 需要和左边的 .col-md-9 保持高度一致即可,加上这行代码:

$('.side').height($('.main').height())

因为左边的内容区域有图片的延迟加载,所以这行代码需要持续执行:

$(window).scroll(function() { 
 $('.side').height($('.main').height())

 // other code 
 // ...

})

总结:以上就是本篇文的全部内容,希望能对大家的学习有所帮助。更多相关教程请访问 HTML视频教程!

相关推荐:

php公益培训视频教程

以上就是当 position:sticky 遇到 bootstrap 浮动布局时候的踩坑记录的详细内容,更多文章请关注木庄网络博客

相关阅读 >>

用html创建canvas画布生成图片

html abbr标签怎么用

html 编辑器

html中表格动态添加的方法

bootstrap模态框如何加滚动条

html文档由哪几部分组成

html与jsp之间有什么区别

javascript怎么修改html标签属性

html的<article>标签

click在html中用法是什么

更多相关阅读请进入《position:sticky》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...