programing

jQuery를 사용하여 한 요소를 다른 요소에 상대적으로 배치하는 방법은 무엇입니까?

telebox 2023. 5. 17. 22:46
반응형

jQuery를 사용하여 한 요소를 다른 요소에 상대적으로 배치하는 방법은 무엇입니까?

툴바 같은 메뉴가 들어 있는 숨겨진 DIV가 있습니다.

마우스가 메뉴 위에 있을 때 메뉴 DIV를 표시할 수 있는 DIV가 여러 개 있습니다.

메뉴 DIV를 활성(마우스 호버) DIV의 오른쪽 상단으로 이동하는 내장 기능이 있습니까?저는 그런 것을 찾고 있습니다.$(menu).position("topright", targetEl);

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>

그런 다음 다음 JavaScript 코드를 사용할 수 있습니다.

$(".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();
});

하지만 효과가 없어요!

메뉴와 자리 표시자가 동일한 간격띄우기 상위 항목을 가지고 있는 동안에는 이 작업이 수행됩니다.만약 그들이 그렇지 않고, 당신이 DOM의 어디에 상관하는 중첩된 CSS 규칙이 없다면.#menu요소는 다음을 사용합니다.

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

위치를 지정하는 선 바로 앞에#menu원소의

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

이 접근 방식에서는 작동하지 않는 이상한 레이아웃이 있을 수 있습니다.이 경우 jQuery.ui의 위치 플러그인(아래 답변에서 언급한 대로)을 사용하면 됩니다. 이 플러그인은 모든 예상 가능한 이벤트를 처리합니다.참고로 다음 작업을 수행해야 합니다.show()호출 전 메뉴 요소position({...})플러그인이 숨겨진 요소를 배치할 수 없습니다.

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

(원래 솔루션은 여기에 보관되어 있습니다.)

그래서, 제가 여기서 가졌던 원래의 방법은 이상과는 거리가 먼 것으로 밝혀졌습니다.특히 다음과 같은 경우 실패합니다.

  • 메뉴의 간격띄우기 상위가 자리 표시자의 간격띄우기 상위가 아닙니다.
  • 자리 표시자에 테두리/경계가 있음

운 좋게도, jQuery는 방법을 소개했습니다 (position()그리고.outerWidth())1.2.6으로 거슬러 올라가면 후자의 경우에서 올바른 값을 훨씬 쉽게 찾을 수 있습니다.전자의 경우에는,append메뉴 요소를 자리 표시자에 연결하면 작동하지만 중첩을 기반으로 하는 CSS 규칙을 위반합니다.

참고: 여기에는 jQuery UI(jQuery뿐만 아니라)가 필요합니다.

이제 다음을 사용할 수 있습니다.

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

빠른 포지셔닝(jQuery UI/Position)을 위해 사용합니다.

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

이것이 결국 저에게 효과가 있었던 것입니다.

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();
};

요소를 배치하는 데 도움이 되는 jQuery 함수가 있습니다.

다음은 사용 예입니다.

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

위의 코드는 #el1의 오른쪽 하단과 #el2의 오른쪽 상단을 맞춥니다.['cc', 'cc']는 #el2에서 #el1을 중심으로 합니다.#el1이 위치의 css를 가지고 있는지 확인합니다: 절대 및 z-index: 10000 (또는 정말 큰 숫자).

오프셋 옵션을 사용하면 지정된 픽셀 수만큼 좌표를 지정할 수 있습니다.

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

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'
  });

}

왜 너무 복잡하죠?솔루션은 매우 간단합니다.

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();
})

효과가 있다고 해도,

  • 다른 곳에 두 개의 디브가 배치되었습니다.
  • 브라우저 크기 조정

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

이 플러그인에는 충돌 처리(뒤집기)도 포함되어 있으므로 도구 모음과 같은 메뉴를 보이는 위치에 배치할 수 있습니다.

$(".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/

이런 거?

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

이것은 나에게 도움이 됩니다.

var posPersonTooltip = function(event) {
var tPosX = event.pageX - 5;
var tPosY = event.pageY + 10;
$('#personTooltipContainer').css({top: tPosY, left: tPosX});

언급URL : https://stackoverflow.com/questions/158070/how-to-position-one-element-relative-to-another-with-jquery

반응형