Nice programing

수직으로 고정 된 위치 요소, 절대 수평으로 고정

nicepro 2020. 10. 30. 20:57
반응형

수직으로 고정 된 위치 요소, 절대 수평으로 고정


내가 달성하려는 것은 다음과 같습니다.

div의 오른쪽에서 특정 거리에 위치하고 뷰포트의 크기에 관계없이 항상 div 측면에서 같은 거리에있는 버튼이 필요하지만 창과 함께 스크롤됩니다.

따라서 항상 div의 오른쪽에서 x 픽셀이지만 항상 뷰 포트의 상단에서 y 픽셀입니다.

이것이 가능한가?


다른 요소를 기준으로 수평으로 고정 요소 배치

( 면책 조항 참고 : 여기제공된 솔루션은 질문 제목에 명시된 것처럼 기술적으로 " 절대 수평 "이 아니지만 OP가 원래 원했던 것을 달성했습니다. 고정 위치 요소는 다른 오른쪽 가장자리에서 'X'거리가되지만 고정 위치에 있습니다. 수직 스크롤.)

나는 이러한 유형의 CSS 도전을 좋아합니다. 개념 증명으로 네, 원하는 것을 얻을 수 있습니다 . 필요에 따라 몇 가지를 조정해야 할 수도 있지만 여기에는 FireFox, IE8 및 IE7을 통과 한 샘플 html 및 css가 있습니다 (물론 IE6에는 없습니다 position: fixed).

HTML :

<body>
  <div class="inflow">
    <div class="positioner"><!-- may not be needed: see notes below-->
      <div class="fixed"></div>
    </div>
  </div>
</body>

CSS (데모 용 테두리 및 모든 치수) :

div.inflow {
  width: 200px; 
  height: 1000px; 
  border: 1px solid blue; 
  float: right; 
  position: relative; 
  margin-right: 100px;
}
div.positioner {position: absolute; right: 0;} /*may not be needed: see below*/
div.fixed {
  width: 80px; 
  border: 1px solid red; 
  height: 100px; 
  position: fixed; 
  top: 60px; 
  margin-left: 15px;
}

핵심의 수평에 대해 left또는 전혀 설정하지 않고 두 개의 래퍼 div를 사용하여 수평 위치를 설정하는 것입니다. 되어 있지 (가) 필요한 경우 , 고정 폭 인이 왼쪽 가장자리로, 용기의 특정 폭으로 설정 될 수있다. 그러나 컨테이너보다 너비를 백분율 로 지정하려면을 첫 번째 오른쪽 으로 밀어야합니다 .rightdiv.fixeddiv.positionerdiv.inflowdiv.fixeddiv.positionerdiv.fixeddiv.inflow

편집 : 내가 설정 흥미로운 보조 노트로서 overflow: hidden(한 필요가 그렇게해야)이이에 div.inflow없었다 효과 의 다른 경계 밖에있는 고정 위치 DIV에 있습니다. 분명히 고정 위치는 포함 div의 컨텍스트에서 제거하기에 충분합니다 overflow.


이 게시물을 포함하여 많은 파고 끝에 내가 좋아하는 솔루션을 찾을 수 없었습니다. 여기서 Accepted Answer는 OP의 제목이 읽은 것을 수행하지 않으며 내가 찾을 수있는 최상의 솔루션은 의심스러운 요소를 초래했습니다. 그런 다음 저를 때렸습니다. 요소를 "고정"하고 수평 스크롤이 발생하는시기를 감지하고 절대 위치로 전환합니다. 결과 코드는 다음과 같습니다.

코드 펜으로 봅니다.

HTML

  <div class="blue">
    <div class="red">
    </div>
  </div>

CSS

/* Styling */
.blue, .red {
  border-style: dashed;
  border-width: 2px;
  padding: 2px;
  margin-bottom: 2px;
}

/* This will be out "vertical-fixed" element */
.red {
  border-color: red;
  height: 120px;
  position: fixed;
  width: 500px;
}

/* Container so we can see when we scroll */
.blue {
  border-color: blue;
  width: 50%;
  display: inline-block;
  height: 800px;
}

자바 스크립트

$(function () {
  var $document = $(document),
      left = 0,
      scrollTimer = 0;

  // Detect horizontal scroll start and stop.
  $document.on("scroll", function () {
    var docLeft = $document.scrollLeft();
    if(left !== docLeft) {
      var self = this, args = arguments;
      if(!scrollTimer) {
        // We've not yet (re)started the timer: It's the beginning of scrolling.
        startHScroll.apply(self, args);
      }
      window.clearTimeout(scrollTimer);
      scrollTimer = window.setTimeout(function () {
        scrollTimer = 0;
        // Our timer was never stopped: We've finished scrolling.
        stopHScroll.apply(self, args);
      }, 100);
      left = docLeft;
    }
  });

  // Horizontal scroll started - Make div's absolutely positioned.
  function startHScroll () {
    console.log("Scroll Start");
    $(".red")
    // Clear out any left-positioning set by stopHScroll.
    .css("left","")
    .each(function () {
      var $this = $(this),
          pos = $this.offset();
      // Preserve our current vertical position...
      $this.css("top", pos.top)
    })
    // ...before making it absolutely positioned.
    .css("position", "absolute");
  }

  // Horizontal scroll stopped - Make div's float again.
  function stopHScroll () {
    var leftScroll = $(window).scrollLeft();
    console.log("Scroll Stop");
    $(".red")
    // Clear out any top-positioning set by startHScroll.
    .css("top","")
    .each(function () {
      var $this = $(this), 
        pos = $this.position();
      // Preserve our current horizontal position, munus the scroll position...
      $this.css("left", pos.left-leftScroll);
    })
    // ...before making it fixed positioned.
    .css("position", "fixed");
  }
});

I arrived here looking for a solution to a similar problem, which was to have a footer bar that spans the width of the window and sits below the (variable height and width) content. In other words, make it appear that the footer is "fixed" with respect to its horizontal position, but retains its normal postion in the document flow with respect to its vertical position. In my case, I had the footer text right-aligned, so it worked for me to dynamically adjust the width of the footer. Here is what I came up with:

HTML

<div id="footer-outer">
<div id="footer">
    Footer text.
</div><!-- end footer -->
</div><!-- end footer-outer -->

CSS

#footer-outer
{
    width: 100%;
}
#footer
{
    text-align: right;
    background-color: blue;
    /* various style attributes, not important for the example */
}

CoffeeScript / JavaScript

(Using prototype.js).

class Footer
document.observe 'dom:loaded', ->
    Footer.width = $('footer-outer').getDimensions().width
Event.observe window, 'scroll', ->
    x = document.viewport.getScrollOffsets().left
    $('footer-outer').setStyle( {'width': (Footer.width + x) + "px"} )

which compiles into:

Footer = (function() {

  function Footer() {}

  return Footer;

})();

document.observe('dom:loaded', function() {
  return Footer.width = $('footer-outer').getDimensions().width;
});

Event.observe(window, 'scroll', function() {
  var x;
  x = document.viewport.getScrollOffsets().left;
  return $('footer-outer').setStyle({
    'width': (Footer.width + x) + "px"
  });
});

This works nicely in FireFox, and pretty well in Chrome (it's a little jittery); I haven't tried other browsers.

I also wanted any spare space below the footer to be a different colour, so I added this footer-stretch div:

HTML

...
</div><!-- end footer -->
<div id="footer-stretch"></div>
</div><!-- end footer-outer -->

CSS

#footer-outer
{
    height: 100%;
}
#footer-stretch
{
    height: 100%;
    background-color: #2A2A2A;
}

Note that for the #footer-stretch div to work, all the parent elements up to the body element (and possibly the html element - not sure) must have a fixed height (in this case, height = 100%).

참고URL : https://stackoverflow.com/questions/3303173/position-element-fixed-vertically-absolute-horizontally

반응형