CSS位置已修复。 Div包装器必须垂直固定,但必须水平变化

时间:2012-06-04 20:23:46

标签: javascript jquery html css

我有一个div,就像这样

  #footer
   {   position:fixed;
       left:40px;
       top:0px; 
   }

垂直或水平滚动时,位置固定。但是我想在用户垂直滚动滚动条时修复div,但是当用户水平滚动滚动条时应该会改变。

我见过一些论坛和帖子,但大多数时候我发现了jquery脚本。我想知道是否有办法在CSS中做到这一点?

Fixed position in only one direction 我读过这篇文章,但我不理解jquery脚本。请告诉我在css中执行此操作的方法或使用jquery执行此操作的更好方法。谢谢

4 个答案:

答案 0 :(得分:6)

似乎不可能只用CSS / HTML让这个“看起来很好”。 正如RuupFixed position in only one direction所提到的,为JS分层,是一个不错的选择。

幸运的是,我找到了一种让它以某种方式工作的方法(不那么漂亮): http://jsfiddle.net/MKEbW/5/

HTML(在body标签内):

<div id="simulated-html">
    <div id="footer">
        <span>
            <!-- Footer text here -->
        </span>
    </div>
    <div id="simulated-body">
        <!-- Your website here -->
    </div>
</div>

CSS:

* { margin:0; padding:0; }

html {
    font: 12px/1.5em Georgia;
}
p { padding: 5px; }

html, body {
    height: 100%;
    overflow: hidden; /* hide scrollbars, we create our own */
}

#simulated-html {
    background: orange;
    overflow-x: scroll; /* force horizontal scrollbars (optional) */
    overflow-y: hidden; /* hide. we use the #simulated-body for it. */
    position: relative; /* to align #footer on #simulated-html */
    height: 100%;
}

#simulated-body {
    overflow-y: scroll; /* force vertical scrollbars (optional) */
    overflow-x: hidden; /* hide. we use the #simulated-html for it. */
    height: 100%;
    background: #eee;

    /* use as a container */
    width: 450px;
    margin: 0 auto;
}

#footer {
    position: absolute;
    bottom: 0px; /* vertical align it to #simulated-html */
    width: 100%;
    background: red;
    z-index: 99; /* always show footer */
    color: white;
}
#footer span {
    width: 450px;
    margin: 0 auto;
    background: green;
    display: block;
}

似乎可以在IE7 +和现代浏览器中工作,通过browserlab.adobe.com进行测试。

在Chrome 18中使用滚动条,更小和更宽的视口进行测试。

我建议不支持浏览器和/或JS解决方法的后备。

答案 1 :(得分:1)

链接的帖子正是您所需要的。您可以复制确切的脚本。

$(window).scroll(function(){
$('#footer').css('left','-'+$(window).scrollLeft());
});

div css是这样的(当它有0px时可能不是页脚:P但是没问题)

#footer
{  position:fixed;
   left:40px;
   top:0px; 
}

滚动jquery脚本时,只需将左(x)坐标调整为与窗口scrollLeft相同的值。

答案 2 :(得分:1)

以前的代码有一个小修复。

用于水平移动固定div的已更改的javascript代码

$(window).scroll(function(){
  $('#footer').css('left',-$(window).scrollLeft());
});

答案 3 :(得分:0)

横轴应该如何变化?这个代码目前的方式是它始终保持从左边40px。为了使左边距相对于窗口大小改变位置,必须使用百分比和负边距。例如,以固定的div为中心:

     #centered { 
          height: 350px;
          top: 0;  
          position: fixed;
          width: 1024px; 
          left: 50%; 
          margin-left: -512px; 
          z-index: 9999;
          }

请注意,您的负边距必须是div的宽度HALF。如果你想要40px到中心的左边那么你会再添加40px到margin-left。