首页 > 解决方案 > 如何将 $watch 用于 getBoundingClientRect()

问题描述

我有一个 iframe,当源更新为 iframe 时,根据加载时间(有些包含图像,因此需要时间来加载)iframe 的宽度和高度,即;getBoundingClientRect()变化。所以每次我想触发事件时,如何使用触发器使用$watch.

标签: javascriptangularjs

解决方案


第一种方法:

您可以使用 $scope.$watch() 观看函数

HTML

<div ng-app="myApp" ng-controller="myCtrl">
   <div id="header">Example Header</div>
</div

JS

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
   let h = document.getElementById('header');

   $scope.$watch(function(){
      return h.getBoundingClientRect();
   }, function(newValue, oldValue){
      console.info("log", newValue, oldValue);
   });

});

第二种方法:

MutationObserver:MutationObserver 接口提供了监视对 DOM 树所做更改的能力。( https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver )

快乐编码!!!


推荐阅读