programing

jquery - 디브가 높이를 변경하는지 또는 CSS 속성을 변경하는지 확인하는 방법은 무엇입니까?

codeshow 2023. 10. 24. 21:36
반응형

jquery - 디브가 높이를 변경하는지 또는 CSS 속성을 변경하는지 확인하는 방법은 무엇입니까?

디브가 높이를 변경하거나 CSS 속성을 변경할 때 이벤트를 트리거하려면 어떻게 해야 합니까?

아이디가 =인 디브가 있습니다.mainContent. jquery가 높이를 변경하면 이벤트가 자동으로 트리거되도록 하고 싶습니다.저는 이런 짓을 했습니다.

$("#mainContent").change('height', function() {
    $("#separator").css('height', $("#mainContent").height());
});

틀렸다는 걸 압니다.

내 전체 코드는 다음과 같습니다. (모르는 이유로 jsfiddle에 들어갈 수 없기 때문에 모든 코드를 붙여넣었습니다.)

$(document).ready(function() {
 $("#separator").css('height', $("body").height());
});

$(function() {
 $("#btnSample1").click(function() {
  $("#mainContent").css('height', '400px');
  $("#mainContent").css('width', '600px');
  $("#mainContent").css('background-color', '#F0F0F0');
 });

 $("#btnSample2").click(function() {
  $("#mainContent").css('height', '1600px');
  $("#mainContent").css('width', '700px');
  $("#mainContent").css('background-color', '#F0F0F0');     
 });

 $("#mainContent").change('height', function() {
  $("#separator").css('height', $("#mainContent").height());
 });
});
html, body {
 width: 100%;
 height: 100%;
 margin: 0;
 padding: 0;
}

#separator {
 border-right: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table style="width: 100%;">
 <tr>
  <td valign="top" style="width: 19%;"> 
   <table id="mainMenu">
    <tr><td><input id="btnSample1" type="button" value="Sample 1"  /></td></tr>
    <tr><td><input id="btnSample2" type="button" value="Sample 2"  /></td></tr>
   </table>
  </td>

  <td valign="top" style="width: 1%;" >
   <div id="separator"></div> 
  </td>

  <td valign="top" style="width: 80%;">
   <div id="mainContent"></div>
  </td>
 </tr>
</table>

divid=의 높이를 조정하려고 합니다.separator의 높이를 기준으로mainContent한창 일 때마다mainContent변화들.

추신: 이 경우 버튼 이벤트를 사용하여 이 작업을 수행할 수 있다는 것을 알고 있지만 높이가 변경되었을 때 디브가 이벤트를 트리거했으면 합니다.

첫째, 그런 css-changes 이벤트는 처음부터 없지만, 다음과 같이 자체적으로 생성할 수 있습니다.onchange을 위한.:input요소만.CSS 변경의 경우가 아닙니다.

CSS 변경을 추적하는 두 가지 방법이 있습니다.

  1. x번(예에서는 500밀리초)마다 dom 요소의 css 변경 여부를 검사합니다.
  2. 요소 css를 변경할 때 이벤트를 트리거합니다.
  3. 사용.DOMAttrModified돌연변이 사건.하지만 감가상각이 됐으니 생략하겠습니다.

첫번째 방법:

var $element = $("#elementId");
var lastHeight = $("#elementId").css('height');
function checkForChanges()
{
    if ($element.css('height') != lastHeight)
    {
        alert('xxx');
        lastHeight = $element.css('height'); 
    }

    setTimeout(checkForChanges, 500);
}

두번째 방법:

$('#mainContent').bind('heightChange', function(){
        alert('xxx');
    });


$("#btnSample1").click(function() {
    $("#mainContent").css('height', '400px');
    $("#mainContent").trigger('heightChange'); //<====
    ...
});    

CSS 변경을 제어한다면 두 번째 옵션은 훨씬 우아하고 효율적인 방법입니다.

설명서:

  • 바인딩:Description: Attach a handler to an event for the elements.
  • 트리거:Description: Execute all handlers and behaviors attached to the matched elements for the given event type.

여기서는 다른 답변에 설명된 기법을 사용하지 마십시오.그들은 css3 애니메이션 크기 변경, 플로팅 레이아웃 변경 또는 jQueryland에서 오지 않는 변경으로 작동하지 않습니다.CPU 시간을 낭비하지 않는 이벤트 기반 방식인 크기 조정 탐지기를 사용할 수 있습니다.

https://github.com/marcj/css-element-queries

해당 용도로 사용할 수 있는 RizeSensor 클래스가 포함되어 있습니다.

new ResizeSensor(jQuery('#mainContent'), function(){ 
    console.log('main content dimension changed');
});

면책 사항:나는 이 도서관을 썼습니다.

나중을 위해서 제가 글을 올리겠습니다.< IE11을 지원할 필요가 없는 경우 MutationObserver를 사용해야 합니다.

다음은 caniuse js mutationObserver 링크입니다.

간편한 사용과 강력한 결과.

    var observer = new MutationObserver(function (mutations) {
        //your action here
    });

    //set up your configuration
    //this will watch to see if you insert or remove any children
    var config = { subtree: true, childList: true };

    //start observing
    observer.observe(elementTarget, config);

더 이상 관찰할 필요가 없으면 연결을 끊으십시오.

    observer.disconnect();

자세한 내용은 MDN 문서를 확인하십시오.

또 하나의 간단한 예.

이 샘플의 경우 100x100 DIV-box를 사용할 수 있습니다.

<div id="box" style="width: 100px; height: 100px; border: solid 1px red;">
 // Red box contents here...
</div>

그리고 작은 jQuery 트릭:

<script type="text/javascript">
  jQuery("#box").bind("resize", function() {
    alert("Box was resized from 100x100 to 200x200");
  });
  jQuery("#box").width(200).height(200).trigger("resize");
</script>

단계:

  1. 작업 크기를 조정하기 위한 DIV 블록 요소를 만들었습니다.
  2. 간단한 자바스크립트 코드를 다음과 같이 추가합니다.
    • jQuery bind
    • j트리거 동작 "크기 조정"이 포함된 jQuery resizer - 트리거는 예제에서 가장 중요한 것입니다.
  3. 크기를 조정한 후 브라우저 알림 정보를 확인할 수 있습니다.

그게 다에요 ;-)

높이 또는 다른 차원 매개변수에 관해서는 관찰자 크기 조정 인터페이스를 사용할 수 있습니다.먼저 HTML 요소를 얻습니다.

const divElem = document.querySelector('#mainContent');

요소 유형은 DIV로 제한되지 않으며, 무엇이든 가능합니다.그런 다음 관찰자 크기 조정 인터페이스의 인스턴스를 만듭니다.

let myObserver = new ResizeObserver(entries => {
  console.log("Height changed. New height: "+$("#mainContent").height());
});

마지막으로 지정된 요소를 시작하는 관찰() 메서드를 호출합니다.

myObserver.observe(divElem);

요소의 크기가 조정될 때마다 Observ() 메서드가 트리거됩니다.

참고: 관찰자 크기 조정 인터페이스는 Internet Explorer에서 작동하지 않습니다.

그 밖에 중요한 답변은 다음과 같습니다.DIV의 차원이 변경된 것을 감지하는 방법은?

언급URL : https://stackoverflow.com/questions/9628450/jquery-how-to-determine-if-a-div-changes-its-height-or-any-css-attribute

반응형