【问题标题】:Is there a way to detect reflows instantly in Angular, without using $timeout?有没有办法在 Angular 中立即检测回流,而不使用 $timeout?
【发布时间】:2015-04-21 16:19:46
【问题描述】:

我正在使用可滚动的画布列表来绘制数据的网站上工作,并且每当它们所在的 div 的宽度发生变化时,我都需要调整画布的大小。

我在大多数情况下都可以使用它,但是如果我删除了一个使滚动条消失的绘图,它就不起作用了。我尝试了以下方法,其中 plotsScroller 是带有滚动条的 div,而 plotsList 是其中的内容:

    $scope.isScrollingPlotsList = function() {
        return plotsList.offsetHeight > plotsScroller.offsetHeight;
    }

    $scope.$watch('isScrollingPlotsList()', $scope.$apply);

这段代码可以工作除了,在移除滚动条的回流之后不会发生$digest$digest 在我删除绘图时被调用,但我猜回流会在稍后发生。

有谁知道我如何在不使用$timeout 的情况下检测回流?

【问题讨论】:

    标签: html angularjs canvas scrollbar reflow


    【解决方案1】:

    您可以使用Mutation Observers 来检测 DOM 中的更改。当发生更改时,您会收到通知,并且可以遍历以查看更改的内容。

    使用示例(source):

    // select the target node
    var target = document.querySelector('#some-id');
    
    // create an observer instance
    var observer = new MutationObserver(function(mutations) {
      mutations.forEach(function(mutation) {
        console.log(mutation.type);
      });    
    });
    
    // configuration of the observer:
    var config = { attributes: true, childList: true, characterData: true };
    
    // pass in the target node, as well as the observer options
    observer.observe(target, config);
    
    // later, you can stop observing
    observer.disconnect();
    

    有关详细信息,另请参阅源链接。

    所有主流浏览器都应该支持它,包括。 IE11。对于 [IE9, IE11> 有一个可以使用的polyfill

    The specification

    【讨论】:

    • 我没听说过 Mutation Observers,那太好了!现在只要我能说服我的老板停止支持 IE
    • 添加了 polyfill 的链接 :-)
    • 据该网站称,“这使用 MutationEvents 来实现 MutationObserves,因此您至少需要 IE9。”
    猜你喜欢
    • 2012-02-18
    • 2021-10-12
    • 2018-09-15
    • 2020-09-21
    • 1970-01-01
    • 1970-01-01
    • 2020-12-20
    • 1970-01-01
    • 2021-04-10
    相关资源
    最近更新 更多