【问题标题】:How to let a fixed "sticky" div stay outside the viewport如何让固定的“粘性”div 留在视口之外
【发布时间】:2012-02-21 21:23:02
【问题描述】:

我正在尝试学习本教程:http://jqueryfordesigners.com/fixed-floating-elements/

问题在于,每当将固定定位应用于 div 时,如果浏览器宽度发生变化,则 div 会水平移动以适应视口。在教程示例http://static.jqueryfordesigners.com/demo/fixedfloat.html 中不会发生这种情况。

这是我的代码(一切都在相对定位的#wrapper 中):

CSS:

        #cart {
            position: absolute;
            right: 0;
            width: 270px;
        }

        #target {
            width: 270px;
            height: 200px;

            background-color: blue;
            background-position: 50% 50%;
            background-repeat: no-repeat;

            position: absolute;
            top: 250px;
            right: 0;

            padding: 0;
            border-radius: 15px 15px 0 0 ;
        }

        #drag-here {
            width: 270px;
            height: 0;

            background-image: url(drag-here.png);
            background-repeat: no-repeat;
            display: none;

            position: absolute;
            top: 470px;
            right: 0;
        }

        #cart-list {
            display: none;
            position: absolute;
            top: 430px;
            right: 0;

            list-style-type: none;
        }

        .sticky #target {position: fixed; top: 5px;}
        .sticky #drag-here {position: fixed; top: 225px;}
        .sticky #cart-list {position: fixed; top: 185px;}

HTML:

<section id="cart">
    <div id="target" class="target-listen"></div>
    <div id="drag-here"></div>
    <ul id="cart-list">
    </ul>
</section>

JQuery:

sticky = false;
initialOffset = $("#target").offset().top - 5;
$(window).scroll(function () {
    if ($(this).scrollTop() >= initialOffset) {
        if (!sticky) {
            $("#cart").addClass("sticky");
            sticky = true;
        } 
    }
    else {
        if (sticky) {
            $("#cart").removeClass("sticky");
            sticky = false;
        }
    }
});

你可以在这里看到我的页面:http://www.brandcoffee.it/test/brandapart/imagick.php

【问题讨论】:

  • 如果你想在视口之外使用容器元素。为视口设置固定宽度,例如 1000px。如果视口现在只有 800px 宽,那么剩下的 200px 就会被剪掉。如果它在您页面的右侧,它包括您的粘性物品

标签: jquery scroll positioning sticky


【解决方案1】:

我认为删除 #target 中的 right : 0; 应该可以。

【讨论】:

  • 确实做到了!我不得不删除正确的:0;在所有兄弟姐妹 div 中也是如此。
      仍然没有正确对齐。
  • 好的,好像是内联/块问题。我用 div 替换了
    • s,一切都按预期工作。
【解决方案2】:

尝试在ratio(或百分比)中提供width 属性,而不是固定像素值。 如:

width:25%; //for #target, and
float:right; //make target float right

width:75%; // for other contents on left side

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-03
    • 1970-01-01
    • 1970-01-01
    • 2019-08-10
    • 1970-01-01
    • 2023-01-21
    • 1970-01-01
    相关资源
    最近更新 更多