使两个元素具有相同的大小

Make two elements have the same size

本文关键字:元素 两个      更新时间:2023-09-26

我希望DOM树中位于不同位置和不同"父级"的两个元素具有相同的高度和宽度,即使其中一个发生了更改。

有没有一个解决方案可以支持包括IE 8在内的所有浏览器?

编辑:如果有一个解决方案在IE 8上不起作用,我仍然想听听,但它不会被接受为我正在寻找的解决方案。

澄清:我想解决大小更改的任何原因:窗口大小更改、内容大小更改等。

您可以使用setInterval来执行您想要的操作。

var changeIndex = -1; // record element width or height is change or not
function setToSame() {
    if(changeIndex!=-1) {
        console.log("test");
    $('.same').height($('.same').eq(changeIndex).height());
    $('.same').width($('.same').eq(changeIndex).width());
        changeIndex = -1;
    }
}
// set your own function to change size, but reserve changeIndex setting
$('input').change(function() {
    $(this).parent().children('.same').css($(this).attr('id'), $(this).val() +'px');
    // set the changeIndex to the current change div
    changeIndex = $('.same').index($(this).parent().children('.same'));
    console.log(changeIndex);
});
setInterval(setToSame, 4);

请参阅此处的jsfiddle。

您可以使用jQuery来获得适用于IE8的解决方案。

假设您想要具有相同高度和宽度的两个元素是,

<div id="fir">
</div>
<div id="sec">
</div>

现在只指定一个元素的高度和宽度为,

#fir{
    height: 50px;
    width: 100px;
}

CSS中没有预定义的方法来检测高度或宽度的变化,但您可以使用jQuery作为来实现结果

$(document).ready(function(){
    $('#fir').bind('heightChange', function(){
        var h = $("#fir").height();
        $("#sec").height(h);
    });
    $('#fir').bind('widthChange', function(){
        var w = $("#fir").width();
        $("#sec").width(w);
    });
    $('#sec').bind('heightChange', function(){
        var h = $("#sec").height();
        $("#fir").height(h);
    });
    $('#sec').bind('widthChange', function(){
        var w = $("#sec").width();
        $("#fir").width(w);
    });
});

这将检测两个元素的高度和宽度变化,并同样设置另一个元素的宽度和高度。

为了检查以上代码是否正常工作,您可以创建一个测试脚本,通过创建一个按钮来更改id="fir"元素的宽度

<button id="btn">Change width</button>

现在包括以下功能,

$("#btn").click(function() {
    $("#fir").css('width', '400px');
    $("#fir").trigger('widthChange'); 
});     

这是它的小提琴

<html>
    <head>
        <style>
            div{}
            #A{background: red}
            #B{background: blue}
        </style>
        <script>
            mBlockChange = false; //Required for IE9-
            function equalSize(f, t){
                mBlockChange = true;
                f = (f || document.getElementById('A'));
                t = (t || document.getElementById('B'));
                //We take the larger dimension of both since it is better than clipping.
                //Change on your demands.
                t.style.height = '';
                t.style.width = '';
                f.style.height = '';
                f.style.width = '';
                t.style.height = Math.max(f.offsetHeight, t.offsetHeight).toString() + 'px';
                t.style.width = Math.max(f.offsetWidth, t.offsetWidth).toString() + 'px';
                f.style.height = Math.max(f.offsetHeight, t.offsetHeight).toString() + 'px';
                f.style.width = Math.max(f.offsetWidth, t.offsetWidth).toString() + 'px';
                setTimeout(function(){mBlockChange = false}, 100);
            }
            //This one for IE9+, FFox, Chrome and Safari
            //http://help.dottoro.com/ljrmcldi.php
            function bindEvents(){
                var tA = document.getElementById('A');
                var tB = document.getElementById('B');
                //The addEventListener() method is not supported in Internet Explorer 8 and earlier versions with resize.
                //Resizing the body
                document.body.onresize = function(){
                    //We only do this once the resizing is actually finished.
                    if (this.Timer) clearTimeout(this.Timer);
                    this.Timer = setTimeout(function(){
                        //console.log('Resize', this);
                        equalSize()
                    }, 300)
                };
                //If supported, we listen on dom changes.
                if ('MutationEvent' in window){
                    document.addEventListener('DOMSubtreeModified', function(){
                        if (document.Timer) clearInterval(document.Timer);
                        //console.log('DOMSubtreeModified', this);
                        if (!mBlockChange) equalSize()
                    }, false);
                }
                //We set an interval for browsers which do not support DOMSubtreeModified
                //If you do not want to rely on ('MutationEvent' in window) put it out of else and cancel the timer (scenario B)
                //Can not bind parameters to setInterval in IE8- :s
                else{
                    document.Timer = setInterval(function(){
                        //console.log('Interval', 'Document');
                        equalSize()
                    }, 1000);
                }
            }
        </script>
    </head>
    <body onload = 'bindEvents()'>
        <div id = 'A'><p contenteditable = 'true'>A</p></div>
        <div id = 'B'><p contenteditable = 'true'>B</p></div>
    </body>
</html>

https://jsfiddle.net/5cn7maqe/

然而,元素的高度和宽度不应该神奇地改变,它总是需要一些交互,比如通过ajax更改dom、输入内容可编辑或调整窗口大小。您最好在这些操作之后手动调整它。

编辑:做了一些小改动。https://jsfiddle.net/5cn7maqe/1/