简体   繁体   English

绝对定位,但仅在div内

[英]Absolute positioning but only inside div

I am having issues with sticky javascript function which allows fixed positioning of the div. 我在粘性javascript函数上存在问题,该函数允许div的固定位置。

This is the function: 这是功能:

$(function(){ // document ready
  if (!!$('.sticky').offset()) { // make sure ".sticky" element exists
    var stickyTop = $('.sticky').offset().top; // returns number 
    $(window).scroll(function() { // scroll event
      var windowTop = $(window).scrollTop(); // returns number 
      if (stickyTop < windowTop) {
    $('.sticky').css({ position: 'fixed', width: 'inherit', top: 10 });
      } else {
    $('.sticky').css('position','static');
      }
    });
  }
});

But I need that to happen only inside the parent div, not the whole page. 但是我需要仅在父div内部而不是整个页面内发生。 Here is the example: 这是示例:

http://www.astroprodavnica.com/59/izrada-i-tumacenje-natalne-karte.html http://www.astroprodavnica.com/59/izrada-i-tumacenje-natalne-karte.html

It is the div on the right. 它是右边的div。

Parent div should have position: relative or any other than static , which is used by default. div position: relative应为position: relative或除static以外的任何其他position: relative (默认情况下使用)。

Then to position inside this parent, child should have position: absolute . 然后,要定位在该父对象中,子对象应具有position: absolute

You can read more about positioning eg here . 您可以在此处阅读有关定位的更多信息。

while you use fixed position you need to use (relative parent position will not work with fixed child) 当您使用固定职位时,您需要使用(相对父职位不适用于固定子职位)

if (windowTop > stickyTop 
  && windowTop < $('.right').offset().top + $('.right').outerHeight(true)) {
    $('.sticky').css({ position: 'fixed', width: 'inherit', top: 10 });
  }else if(windowTop < stickyTop ){
     $('.sticky').css('position','static');
  }else{
    $('.sticky').css('position','absolute').css('bottom', '0px');
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM