복붙노트

[JQUERY] 어떻게 jQuery로 다른 하나의 요소에 상대적인 위치를 하는가?

JQUERY

어떻게 jQuery로 다른 하나의 요소에 상대적인 위치를 하는가?

해결법


  1. 1.참고 :이 jQuery를 UI (단지 jQuery를)가 필요합니다.

    참고 :이 jQuery를 UI (단지 jQuery를)가 필요합니다.

    이제 사용할 수 있습니다 :

    $("#my_div").position({
        my:        "left top",
        at:        "left bottom",
        of:        this, // or $("#otherdiv")
        collision: "fit"
    });
    

    고속 위치 결정 (jQuery를 UI / 위치).

    여기 jQuery를 UI를 다운로드 할 수 있습니다.


  2. 2.TL; DR : (여기를보십시오)

    TL; DR : (여기를보십시오)

    경우 다음과 같은 HTML을 가지고 :

    <div id="menu" style="display: none;">
       <!-- menu stuff in here -->
       <ul><li>Menu item</li></ul>
    </div>
    
    <div class="parent">Hover over me to show the menu here</div>
    

    당신은 다음과 같은 자바 스크립트 코드를 사용할 수 있습니다 :

    $(".parent").mouseover(function() {
        // .position() uses position relative to the offset parent, 
        var pos = $(this).position();
    
        // .outerWidth() takes into account border and padding.
        var width = $(this).outerWidth();
    
        //show the menu directly over the placeholder
        $("#menu").css({
            position: "absolute",
            top: pos.top + "px",
            left: (pos.left + width) + "px"
        }).show();
    });
    

    그러나 그것은 작동하지 않습니다!

    이것은 한 메뉴와 자리가 동일한 오프셋 부모가 같이 작동합니다. 그렇지 않은, 당신은하지 않도록주의 중첩 된 CSS 규칙이있는 경우 어디 DOM에서 #menu 요소이며, 사용 :

    $(this).append($("#menu"));
    

    단지 #menu 요소를 배치합니다 라인 전에.

    하지만 여전히 작동하지 않습니다!

    이 접근 방식으로 작동하지 않는 몇 가지 이상한 레이아웃이있을 수 있습니다. 이 경우에, 단지 모든 가능한 사태를 처리 (이하 응답에서 언급) 플러그인 jQuery.ui의 위치를 ​​사용한다. 당신이 위치를 호출하기 전에) (메뉴 요소를 표시해야합니다 ({...}); 플러그인은 숨겨진 요소를 배치 할 수 없습니다.

    업데이트 2012 년 3 년 후 노트 :

    (원래의 솔루션은 후세 여기 보관)

    그래서, 내가 여기에 있던 원래의 방법은 지금까지 이상에서 것을 밝혀졌습니다. 특히, 경우에 실패합니다 :

    다행히, jQuery를 도입 방법 (위치 ()와 outerWidth ()) 훨씬 쉽게 여기 후자의 경우에 올바른 값을 찾을 수 있도록 1.2.6의 방법으로 다시. 전자의 경우를 들어, 자리의 작품에 메뉴 요소를 추가 (그러나 중첩에 따라 CSS 규칙을 깰 것이다).


  3. 3.이것은 결국 나를 위해 일한 것입니다.

    이것은 결국 나를 위해 일한 것입니다.

    var showMenu = function(el, menu) {
        //get the position of the placeholder element  
        var pos = $(el).offset();    
        var eWidth = $(el).outerWidth();
        var mWidth = $(menu).outerWidth();
        var left = (pos.left + eWidth - mWidth) + "px";
        var top = 3+pos.top + "px";
        //show the menu directly over the placeholder  
        $(menu).css( { 
            position: 'absolute',
            zIndex: 5000,
            left: left, 
            top: top
        } );
    
        $(menu).hide().fadeIn();
    };
    

  4. 4.다음은 나에게 위치 요소를하는 데 도움이 내가 쓴 jQuery를 기능입니다.

    다음은 나에게 위치 요소를하는 데 도움이 내가 쓴 jQuery를 기능입니다.

    다음은 사용 예는 다음과 같습니다

    $(document).ready(function() {
      $('#el1').position('#el2', {
        anchor: ['br', 'tr'],
        offset: [-5, 5]
      });
    });
    

    가지런 위 코드 # EL2의 우측 상단과 # EL1의 오른쪽 하단. [ 'CC', 'CC'는] #에 EL2의 # EL1 중심 것이다. 상단에 유지하기 10000 (또는 정말 많은 수의) : 절대 및 z 인덱스 : 확인 #의 EL1 위치의 CSS를 가지고 있는지 확인하십시오.

    오프셋 옵션을 사용하면 픽셀의 지정된 번호로 좌표를 조금씩 이동 할 수 있습니다.

    소스 코드는 다음과 같습니다 :

    jQuery.fn.getBox = function() {
      return {
        left: $(this).offset().left,
        top: $(this).offset().top,
        width: $(this).outerWidth(),
        height: $(this).outerHeight()
      };
    }
    
    jQuery.fn.position = function(target, options) {
      var anchorOffsets = {t: 0, l: 0, c: 0.5, b: 1, r: 1};
      var defaults = {
        anchor: ['tl', 'tl'],
        animate: false,
        offset: [0, 0]
      };
      options = $.extend(defaults, options);
    
      var targetBox = $(target).getBox();
      var sourceBox = $(this).getBox();
    
      //origin is at the top-left of the target element
      var left = targetBox.left;
      var top = targetBox.top;
    
      //alignment with respect to source
      top -= anchorOffsets[options.anchor[0].charAt(0)] * sourceBox.height;
      left -= anchorOffsets[options.anchor[0].charAt(1)] * sourceBox.width;
    
      //alignment with respect to target
      top += anchorOffsets[options.anchor[1].charAt(0)] * targetBox.height;
      left += anchorOffsets[options.anchor[1].charAt(1)] * targetBox.width;
    
      //add offset to final coordinates
      left += options.offset[0];
      top += options.offset[1];
    
      $(this).css({
        left: left + 'px',
        top: top + 'px'
      });
    
    }
    

  5. 5.이유는 너무 복잡? 해결 방법은 매우 간단합니다

    이유는 너무 복잡? 해결 방법은 매우 간단합니다

    CSS :

    .active-div{
    position:relative;
    }
    
    .menu-div{
    position:absolute;
    top:0;
    right:0;
    display:none;
    }
    

    JQuery와 :

    $(function(){
        $(".active-div").hover(function(){
        $(".menu-div").prependTo(".active-div").show();
        },function(){$(".menu-div").hide();
    })
    

    그것은 경우에도 작동


  6. 6.당신은 PositionCalculator 플러그인 jQuery를 사용할 수 있습니다

    당신은 PositionCalculator 플러그인 jQuery를 사용할 수 있습니다

    툴바와 같은 메뉴가 표시 위치에 배치 할 수 있도록 그 플러그인은 충돌 처리 (플립)를 포함하고있다.

    $(".placeholder").on('mouseover', function() {
        var $menu = $("#menu").show();// result for hidden element would be incorrect
        var pos = $.PositionCalculator( {
            target: this,
            targetAt: "top right",
            item: $menu,
            itemAt: "top left",
            flip: "both"
        }).calculate();
    
        $menu.css({
            top: parseInt($menu.css('top')) + pos.moveBy.y + "px",
            left: parseInt($menu.css('left')) + pos.moveBy.x + "px"
        });
    });
    

    그 마크 업 :

    <ul class="popup" id="menu">
        <li>Menu item</li>
        <li>Menu item</li>
        <li>Menu item</li>
    </ul>
    
    <div class="placeholder">placeholder 1</div>
    <div class="placeholder">placeholder 2</div>
    

    여기 바이올린은 다음과 같습니다 http://jsfiddle.net/QrrpB/1657/


  7. 7.이 같은?

    이 같은?

    $(menu).css("top", targetE1.y + "px"); 
    $(menu).css("left", targetE1.x - widthOfMenu + "px");
    

  8. 8.이것은 나를 위해 작동합니다 :

    이것은 나를 위해 작동합니다 :

    var posPersonTooltip = function(event) {
    var tPosX = event.pageX - 5;
    var tPosY = event.pageY + 10;
    $('#personTooltipContainer').css({top: tPosY, left: tPosX});
    
  9. from https://stackoverflow.com/questions/158070/how-to-position-one-element-relative-to-another-with-jquery by cc-by-sa and MIT license