ResizeObserver polyfill

For ancient browsers

目前為 2021-11-07 提交的版本,檢視 最新版本

此腳本不應該直接安裝,它是一個供其他腳本使用的函式庫。欲使用本函式庫,請在腳本 metadata 寫上: // @require https://update.cn-greasyfork.org/scripts/435127/986121/ResizeObserver%20polyfill.js

  1. class ResizeObserver {
  2. constructor(callback) {
  3. this.observables = [];
  4. // Array of observed elements that looks like this:
  5. // [{
  6. // el: domNode,
  7. // size: {height: x, width: y}
  8. // }]
  9. this.boundCheck = this.check.bind(this);
  10. this.boundCheck();
  11. this.callback = callback;
  12. }
  13. observe(el) {
  14. if (this.observables.some((observable) => observable.el === el)) {
  15. return;
  16. }
  17. const newObservable = {
  18. el: el,
  19. size: {
  20. height: el.clientHeight,
  21. width: el.clientWidth
  22. }
  23. }
  24. this.observables.push(newObservable);
  25. }
  26. unobserve(el) {
  27. this.observables = this.observables.filter((obj) => obj.el !== el);
  28. }
  29. disconnect() {
  30. this.observables = [];
  31. }
  32. check() {
  33. const changedEntries = this.observables.filter((obj) => {
  34. const currentHeight = obj.el.clientHeight;
  35. const currentWidth = obj.el.clientWidth;
  36. if (obj.size.height !== currentHeight || obj.size.width !== currentWidth) {
  37. obj.size.height = currentHeight;
  38. obj.size.width = currentWidth;
  39. return true;
  40. }
  41. }).map((obj) => obj.el);
  42. if (changedEntries.length > 0) {
  43. this.callback(changedEntries);
  44. }
  45. window.requestAnimationFrame(this.boundCheck);
  46. }
  47. }
  48.  
  49. const fooDiv = document.getElementById('foo');
  50. const barDiv = document.getElementById('bar');
  51.  
  52. const resizeObserver = new ResizeObserver((entries) => {
  53. entries.forEach((entry) => {
  54. const colors = ['#FFDAE9', '#F9FFEF', '#B5FFE1', '#CBE896', '#ACECF7', '#F2BB05'];
  55. entry.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
  56. });
  57. });
  58.  
  59. resizeObserver.observe(fooDiv);
  60.  
  61. resizeObserver.observe(barDiv);