2020. 2. 13. 18:56
반응형

window 같은 경우 resize 이벤트를 통해 크기 변화를 감지할 수 있다.

하지만 div 등의 HTML 태그들은 안되는 것 같다.

그래서 방법을 좀 찾았다.

ResizeObserver 라는게 있긴 했는데 이건 크롬, 오페라, 파이어폭스에서만 되는 것 같다.

엣지, 사파리를 지원해준다면 이걸 쓰는게 좋아보였다.

https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver

 

ResizeObserver

The ResizeObserver interface reports changes to the dimensions of an Element's content or border box, or the bounding box of an SVGElement.

developer.mozilla.org

 

그걸 대체할만한 플러그인을 찾았는데 ResizeSensor라는게 있었다.

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

 

Css-element-queries by marcj

An event-based CSS element dimension query library with valid CSS selector syntax to change styles and allow responsive images based on element's dimensions and not window's viewport. It's exactly what we need when it comes to responsive Web Components. va

marcj.github.io

ResizeSensor를 사용한 다음 요소의 크기가 변하면 width, height를 반환한다.

간단한 사용법은 다음과 같다.

div의 크기가 변하면 div 안에 있는 span에 그 사이즈가 표시되도록 했다.

테스트를 여기 블로그 말고 다른 환경에서 할 때에는 border의 크기도 더해져서 2px 차이가 나기도 했다.

 

width: height:

 

<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/css-element-queries/1.2.3/ResizeSensor.min.js"></script>

<div>
    width: <input type='text' placeholder='width' id="inputWidth"/>
    height: <input type='text' placeholder='height' id="inputHeight"/>
    <button id="testButton">change size</button>
</div>
<div id="testDiv" style="width:200px;height:200px;border:1px solid;resize:both;overflow:auto;">
    <span></span>
</div>
<script>
    $(function(){
        new ResizeSensor($("#testDiv"), function(size){
            $("#testDiv span").text(size.width + "x" + size.height);
            $("#inputWidth").val(size.width);
            $("#inputHeight").val(size.height);
        });

        $("#testButton").click(function(){
            if(isNaN($("#inputWidth").val()) || isNaN($("#inputHeight").val())){
                alert("invalid width or height");
            }else{
                var width = $("#inputWidth").val() + "px";
                var height = $("#inputHeight").val() + "px";
                $("#testDiv").animate({
                    width: width,
                    height: height
                });
            }
            
        })

        /* new ResizeSensor(document.querySelector("#testDiv"), function(size){
            document.querySelector("#testDiv span").innerText = size.width + "x" + size.height;
        }); */
    });
</script>

 

 

 

반응형