How to detect DIV's dimension changed?

后端 未结 25 2361
抹茶落季
抹茶落季 2020-11-22 06:14

I\'ve the following sample html, there is a DIV which has 100% width. It contains some elements. While performing windows re-sizing, the inner elements may be re-positioned,

相关标签:
25条回答
  • 2020-11-22 06:46

    ResizeSensor.js is part of a huge library, but I reduced its functionality to THIS:

    function ResizeSensor(element, callback)
    {
        let zIndex = parseInt(getComputedStyle(element));
        if(isNaN(zIndex)) { zIndex = 0; };
        zIndex--;
    
        let expand = document.createElement('div');
        expand.style.position = "absolute";
        expand.style.left = "0px";
        expand.style.top = "0px";
        expand.style.right = "0px";
        expand.style.bottom = "0px";
        expand.style.overflow = "hidden";
        expand.style.zIndex = zIndex;
        expand.style.visibility = "hidden";
    
        let expandChild = document.createElement('div');
        expandChild.style.position = "absolute";
        expandChild.style.left = "0px";
        expandChild.style.top = "0px";
        expandChild.style.width = "10000000px";
        expandChild.style.height = "10000000px";
        expand.appendChild(expandChild);
    
        let shrink = document.createElement('div');
        shrink.style.position = "absolute";
        shrink.style.left = "0px";
        shrink.style.top = "0px";
        shrink.style.right = "0px";
        shrink.style.bottom = "0px";
        shrink.style.overflow = "hidden";
        shrink.style.zIndex = zIndex;
        shrink.style.visibility = "hidden";
    
        let shrinkChild = document.createElement('div');
        shrinkChild.style.position = "absolute";
        shrinkChild.style.left = "0px";
        shrinkChild.style.top = "0px";
        shrinkChild.style.width = "200%";
        shrinkChild.style.height = "200%";
        shrink.appendChild(shrinkChild);
    
        element.appendChild(expand);
        element.appendChild(shrink);
    
        function setScroll()
        {
            expand.scrollLeft = 10000000;
            expand.scrollTop = 10000000;
    
            shrink.scrollLeft = 10000000;
            shrink.scrollTop = 10000000;
        };
        setScroll();
    
        let size = element.getBoundingClientRect();
    
        let currentWidth = size.width;
        let currentHeight = size.height;
    
        let onScroll = function()
        {
            let size = element.getBoundingClientRect();
    
            let newWidth = size.width;
            let newHeight = size.height;
    
            if(newWidth != currentWidth || newHeight != currentHeight)
            {
                currentWidth = newWidth;
                currentHeight = newHeight;
    
                callback();
            }
    
            setScroll();
        };
    
        expand.addEventListener('scroll', onScroll);
        shrink.addEventListener('scroll', onScroll);
    };
    

    How to use it:

    let container = document.querySelector(".container");
    new ResizeSensor(container, function()
    {
        console.log("dimension changed:", container.clientWidth, container.clientHeight);
    });
    
    0 讨论(0)
  • 2020-11-22 06:47

    Pure Javascript solution, but works only if the element is resized with the css resize button:

    1. store element size with offsetWidth and offsetHeight;
    2. add an onclick event listener on this element;
    3. when triggered, compare curent offsetWidth and offsetHeight with stored values, and if different, do what you want and update these values.
    0 讨论(0)
  • 2020-11-22 06:48
    jQuery(document).ready( function($) {
    
    function resizeMapDIVs() {
    
    // check the parent value...
    
    var size = $('#map').parent().width();
    
    
    
    if( $size < 640 ) {
    
    //  ...and decrease...
    
    } else {
    
    //  ..or increase  as necessary
    
    }
    
    }
    
    resizeMapDIVs();
    
    $(window).resize(resizeMapDIVs);
    
    });
    
    0 讨论(0)
  • 2020-11-22 06:49

    Using Clay.js (https://github.com/zzarcon/clay) it's quite simple to detect changes on element size:

    var el = new Clay('.element');
    
    el.on('resize', function(size) {
        console.log(size.height, size.width);
    });
    
    0 讨论(0)
  • 2020-11-22 06:49

    This blog post helped me efficiently detect size changes to DOM elements.

    http://www.backalleycoder.com/2013/03/18/cross-browser-event-based-element-resize-detection/

    How to use this code...

    AppConfig.addResizeListener(document.getElementById('id'), function () {
      //Your code to execute on resize.
    });
    

    Packaged code used by the example...

    var AppConfig = AppConfig || {};
    AppConfig.ResizeListener = (function () {
        var attachEvent = document.attachEvent;
        var isIE = navigator.userAgent.match(/Trident/);
        var requestFrame = (function () {
            var raf = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame ||
                function (fn) { return window.setTimeout(fn, 20); };
            return function (fn) { return raf(fn); };
        })();
    
        var cancelFrame = (function () {
            var cancel = window.cancelAnimationFrame || window.mozCancelAnimationFrame || window.webkitCancelAnimationFrame ||
                   window.clearTimeout;
            return function (id) { return cancel(id); };
        })();
    
        function resizeListener(e) {
            var win = e.target || e.srcElement;
            if (win.__resizeRAF__) cancelFrame(win.__resizeRAF__);
            win.__resizeRAF__ = requestFrame(function () {
                var trigger = win.__resizeTrigger__;
                trigger.__resizeListeners__.forEach(function (fn) {
                    fn.call(trigger, e);
                });
            });
        }
    
        function objectLoad(e) {
            this.contentDocument.defaultView.__resizeTrigger__ = this.__resizeElement__;
            this.contentDocument.defaultView.addEventListener('resize', resizeListener);
        }
    
        AppConfig.addResizeListener = function (element, fn) {
            if (!element.__resizeListeners__) {
                element.__resizeListeners__ = [];
                if (attachEvent) {
                    element.__resizeTrigger__ = element;
                    element.attachEvent('onresize', resizeListener);
                } else {
                    if (getComputedStyle(element).position === 'static') element.style.position = 'relative';
                    var obj = element.__resizeTrigger__ = document.createElement('object');
                    obj.setAttribute('style', 'display: block; position: absolute; top: 0; left: 0; height: 100%; width: 100%; overflow: hidden; pointer-events: none; z-index: -1;');
                    obj.__resizeElement__ = element;
                    obj.onload = objectLoad;
                    obj.type = 'text/html';
                    if (isIE) element.appendChild(obj);
                    obj.data = 'about:blank';
                    if (!isIE) element.appendChild(obj);
                }
            }
            element.__resizeListeners__.push(fn);
        };
    
        AppConfig.removeResizeListener = function (element, fn) {
            element.__resizeListeners__.splice(element.__resizeListeners__.indexOf(fn), 1);
            if (!element.__resizeListeners__.length) {
                if (attachEvent) element.detachEvent('onresize', resizeListener);
                else {
                    element.__resizeTrigger__.contentDocument.defaultView.removeEventListener('resize', resizeListener);
                    element.__resizeTrigger__ = !element.removeChild(element.__resizeTrigger__);
                }
            }
        }
    })();
    

    Note: AppConfig is a namespace/object I use for organizing reusable functions. Feel free to search and replace the name with anything you would like.

    0 讨论(0)
  • 2020-11-22 06:49

    My jQuery plugin enables the "resize" event on all elements not just the window.

    https://github.com/dustinpoissant/ResizeTriggering

    $("#myElement") .resizeTriggering().on("resize", function(e){
      // Code to handle resize
    }); 
    
    0 讨论(0)
提交回复
热议问题