【问题标题】:Trying to get div to stick at the top while scrolling a page. It is staying at the top but the CSS is getting deformed试图让 div 在滚动页面时停留在顶部。它保持在顶部,但 CSS 正在变形
【发布时间】:2013-12-23 19:46:23
【问题描述】:

我的网站有一种搜索框 div,当用户向下滚动查看数据时,我想将它放在顶部。虽然当我向下滚动时,div 保持在顶部,但一切都变形了。

编辑:我没有为 div 使用任何额外的 CSS。它是 jumbotron 类 div 内的 Bootstrap 容器类 div。

Here is what it ends up looking like.

    <div class="container" id="searcher" style="text-align: center;">
        <h2>Where Do You Want To Go?</h2>
        <input type="text" class="typeahead form-control"></input>

        <div class="btn-group">
            <button type="button" class="btn btn-default dropdown-toggle" id="pType" data-toggle="dropdown">
                Select Permit Type
                <span class="caret"></span>
            </button>
            <ul class="dropdown-menu">
                <li><a href="#">Every Type</a></li>
                <li><a href="#">Commuter Zone A</a></li>
                <li><a href="#">Commuter Zone B</a></li>
                <li><a href="#">Commuter Zone C</a></li>
                <li><a href="#">Commuter Zone D</a></li>
                <li><a href="#">Commuter Zone L</a></li>
                <li><a href="#">Night Commuter</a></li>
                <li><a href="#">Resident Permits</a></li>
                <li><a href="#">Newark and Camden Permits (L)</a></li>
            </ul>
        </div>

    </div>

我正在使用的代码:

function fixDiv() {
    var $cache = $('#searcher');
    if ($(window).scrollTop() > 100)
        $cache.css({'position': 'fixed', 'top': '10px'});
    else
        $cache.css({'position': 'relative', 'top': 'auto'});
}
$(window).scroll(fixDiv);
fixDiv();

【问题讨论】:

  • 能否添加相关的 CSS 代码?
  • 真的没有任何其他的CSS。它只是 jumbotron 类 div 中的一个 Bootstrap 容器类 div。

标签: jquery html css scroll


【解决方案1】:

让我们看看你的 CSS。我很确定您的固定元素需要添加一些不同的样式,因为固定元素不在文档流中,它们不会“适合它们的父元素”和其他奇怪的东西。

此外,与其通过 javascript 设置菜单样式,不如考虑在函数中添加/删除一个类。然后,您可以创建一个不同的 CSS 类来设置菜单样式,并且您可以通过添加该类并刷新页面来调试您的菜单。

if ($(window).scrollTop() > 100)
    $cache.addClass('fixedMenu');
else
    $cache.removeClass('fixedMenu');

然后添加一些css,例如:

#searcher.fixedMenu {
    position: fixed;
    width: 100%;
    etc...
}

【讨论】:

  • 真的没有任何其他的CSS。它只是 jumbotron 类 div 中的一个 Bootstrap 容器类 div。
  • 我知道,但我要说的是,当 div 固定时,您很可能需要一些其他 CSS。请注意,固定的 div 在固定时不会像在另一个 div 内一样。您可能认为会继承的项目不会。
  • 作为一个预感,尝试在固定后增加 div 的宽度,看看你会得到什么结果,因为它看起来菜单只与某些文本一样宽。
  • 明白了。我猜当它的位置固定时,我将不得不以某种方式覆盖容器 div id。我是一名从事网页设计的 Java 开发人员,所以我正在慢慢学习 CSS。
  • 这就是为什么我说添加一个独特的类,我将编辑以向您展示我的意思。
猜你喜欢
  • 1970-01-01
  • 2010-12-05
  • 2017-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-21
  • 2022-12-10
  • 1970-01-01
相关资源
最近更新 更多