【问题标题】:How to make a .fixed sticky item's "margin-top" relative to the size of the sticky item?如何使 .fixed 粘性项目的“margin-top”相对于粘性项目的大小?
【发布时间】:2014-03-30 03:59:26
【问题描述】:

这是我的第一个问题。我在滚动后到达页面顶部时尝试粘贴的图像有问题。 看看这个 jfiddle - 它不是我的,但接近代表我的问题

http://jsfiddle.net/vBy5w/

(我知道我可以输入一个设置的“margin-top”来完成这项工作,但是当浏览器大小发生变化时,图像大小会响应并且会抛出设置的边距。)

到目前为止,我已经通过使用下面的代码来实现我的 html 中的 Div Id = Picture1

<div id="picture1"><img src="img/empty-restaurant.png" alt="Why do your customers not come back?" style="max-width:100%;height:auto;"> </div>

当这张图片“粘住”时,图片下方的测试会跳起来,我通过包含 .js 的最后一行来解决这个问题,但是通过声明一个固定的“margin-top”,这意味着如果根据浏览器大小,边距大小不正确。

有没有办法让这个 Margin 变量或相对于“stick”-ed项目的高度?如果是的话怎么办?

谢谢大家!

$(document).ready(function() {
    var s = $("#picture1");
    var pos = s.position();                    
    $(window).scroll(function() {
        var windowpos = $(window).scrollTop();
        //$("#header_left").html("Distance from top:" + pos.top + "<br />Scroll position: " + windowpos);
        if (windowpos >= pos.top) {
            s.addClass("stick");
        } else {
            s.removeClass("stick"); 
        }

这是需要更改的部分 - 第一个“margin-top”需要相对于“stick”ed 项目的大小

if (windowpos >= pos.top) { s.addClass("stick"); $("body").css("margin-top", 60);     } else { s.removeClass("stick"); $("body").css("margin-top", 0); }

    });
});

【问题讨论】:

  • 请提供jsfiddle.net测试版
  • 这不是我的,而是最接近它的东西...谢谢 Zarich jsfiddle.net/vBy5w
  • 当你说“相对于 s 的大小”时,你是指高度吗?
  • 喜欢 - $("body").css("margin-top", s.height()); ?
  • 抱歉,Rob,是的,我指的是身高。

标签: javascript jquery html margin sticky


【解决方案1】:

作为cmets,

$("body").css("margin-top", s.height());

根据在 window.scroll 期间为 fixed 的元素 (#picture1) 上的高度为 &lt;body&gt; 提供动态 margin-top css 值


另外,您提到高度可能会在屏幕调整大小( rwd )时发生变化

所以这也可以添加(以保持检查)

$(window).resize(function() {
  var s = $("#picture1");
  if(s.hasClass("stick") {
    $("body").css("margin-top", s.height());
  }
});

【讨论】:

    猜你喜欢
    • 2014-06-12
    • 2012-03-02
    • 2018-11-20
    • 1970-01-01
    • 2011-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多