更改大小时有没有办法注意?

时间:2018-08-05 10:54:04

标签: javascript css html-table

我通过CSS resize制作了一个html表,其中包含可调整宽度的单元格。我在<td>的CSS中的设置是:

td {
    resize: horizontal;
    overflow: auto;
    width: 35px;
    min-width: 35px;
}

现在我想知道,如果可以注意到,用户何时更改宽度。因此,在用户更改后,我可以做一些事情。当用户通过CSS resize更改宽度时是否发生事件?

编辑: 为了减少混乱,我将提供一些有关最终目标的详细信息。

我试图达到的最终目标是一个具有固定表头,可滚动表主体和列的表,它们具有可调整大小的宽度(表头和表主体已同步)。

到目前为止,我已经实现了一个具有固定头和可滚动主体的表,以及一个具有可调整宽度的列的表,但没有组合成一个表。

因此,现在我正试图找到一种方法,当调整头部的表格单元格的大小时,可以调整同一列中的主体单元格的宽度(使用JavaScript)。

3 个答案:

答案 0 :(得分:1)

您可以使用javascript onresize事件,如下所示:

window.addEventListener('resize', () => {
    document.getElementById('foo').style.color = 'red';
}) ;
<span id="foo">Resize me</span>

答案 1 :(得分:1)

ResizeObserver API可以解决此问题,还有a polyfill用于尚不支持它的浏览器。

const td = document.querySelector('.right');
const ro = new ResizeObserver((entries, observer) => {
    for (const entry of entries) {
        const {left, top, width, height} = entry.contentRect;

        console.log('Element:', entry.target);
        console.log(`Element's size: ${ width }px x ${ height }px`);
        console.log(`Element's paddings: ${ top }px ; ${ left }px`);
    }
});

ro.observe(td);

const leftElem = document.querySelector('.left');
setInterval(() => {
  leftElem.style.width = `${10 + Date.now() * 0.001 % 50 | 0}px`;
}, 100);
table {
  width: 90%;
  height: 100px;
}
.left {
  background: red;
}
.right {
  background: blue;
}
<script src="https://cdn.rawgit.com/que-etc/resize-observer-polyfill/a3ae98bc/dist/ResizeObserver.global.js"></script>
<table>
  <tr>
    <td class="left"></td>
    <td class="right"></td>
  </tr>
</table>

答案 2 :(得分:0)

在评论中,我从类似的问题中指出了this answer。它帮助我找到了可行的解决方案。

要创建widthChanged事件:

$.event.special.widthChanged = {
    remove: function () {
        $(this).children('iframe.width-changed').remove();
    },
    add: function () {
        var elm = $(this);
        var iframe = elm.children('iframe.width-changed');
        if (!iframe.length) {
            iframe = $('<iframe/>').addClass('width-changed').prependTo(this);
        }
        var oldWidth = elm.width();
        function elmResized() {
            var width = elm.width();
            if (oldWidth != width) {
                elm.trigger('widthChanged', [width, oldWidth]);
                oldWidth = width;
            }
        }

        var timer = 0;
        var ielm = iframe[0];
        (ielm.contentWindow || ielm).onresize = function () {
            clearTimeout(timer);
            timer = setTimeout(elmResized, 1);
        };
    }
}

并使用事件:

$('#id').on('widthChanged', function () {
    // Do what you want, when width changed
});