Bootstrap中nav在container中用affix时,nav宽度撑不满容器的解决方案

    这是我的Bootstrap页面头,我要做的是,当滚动页面到网页标题栏之后,把导航栏固定在页面顶端,适用了Bootstrap的Affix组件;

Bootstrap中nav在container中用affix时,nav宽度撑不满容器的解决方案_第1张图片

    这是我的css片段,我的网页标题高度为80px,当导航栏滚动了80px后,由于如下css设定了top: 0px,

所以会自定固定在页头;

/* 不加上这一行, 当滚动到导航条时,仍然会留出data-offset-top设定的像素的高度 */
div.head.affix{
    top: 0px; /* Set the top position of pinned element */
}



    这是我的页面部分代码;
<body>
		<div class="container">
			<div style="height: 80px">
			  <h1>网站标题 <small> 网站副标题</small></h1>
			</div>
			
			<div class="head " data-spy="affix" data-offset-top="80">
			
				<!-- 默认 navbar navbar-default navbar-fixed-top ; 反色导航条 navbar navbar-inverse navbar-fixed-top --> 
				<nav class="navbar navbar-default" role="navigation">

    这是滚动到80px后的效果;

Bootstrap中nav在container中用affix时,nav宽度撑不满容器的解决方案_第2张图片

    发现导航的宽度,自动适应了内容的宽度,这当然不是我想要的效果,所以我必须借助jquery把导航的宽度设置为container 的宽度;

$('div.head')
	    	  .on('affix.bs.affix', function () {
	    	    var margin =  parseInt($('.container').css("margin-right"));
	    	    var padding = parseInt($('.container').css("padding-right"));
	    	    $("div.head").css("right",margin+padding);
	    	    $("div.head").width($(".container").width());
	    	  })
	    	  .on('affix-top.bs.affix', function () {
	    	    $("div.head").css("right","0px");
	    	    console.log('在滚动到top的高度时,设定div head的宽度为container的宽度:'+$(".container").width());
	    	    $("div.head").width($(".container").width());
	    	  });



    下面来看下效果:

Bootstrap中nav在container中用affix时,nav宽度撑不满容器的解决方案_第3张图片

    完美达到我想要的效果,duang,收工



你可能感兴趣的:(bootstrap,Affix)