• 监听DIV元素尺寸变化


            web开发过程中为了更好的实现元素自适应效果,往往需要监听DIV的尺寸变化。而DIV元素不像window对象,是没有resize事件的,我们无法直接监听DIV的resize事件。因此在需要对DIV元素进行监听时,需要采用一些特定方法完成size的监听。

    方法1: 嵌入iframe方案

            由于iframe元素包含一个window对象,我们可以在要监听的div元素上嵌入一个iframe元素,使其高度和宽度设置为100%,将DIV元素撑满,当DIV尺寸变化时,iframe也会随之变化,我们可以通过监听iframe的resize事件完成间接对DIV元素尺寸变化的监听。

            由此思路编辑js文件如下:

    1. (function () {
    2. var self = this;
    3. /**
    4. * 元素尺寸构造函数
    5. * @param {Object} el 监听元素选择器
    6. */
    7. function ElementResize(eleSelector) {
    8. if (!(this instanceof ElementResize)) return;
    9. if (!eleSelector) return;
    10. this.eleSelector = eleSelector;
    11. this.el = document.querySelector(eleSelector);
    12. this.queue = [];
    13. this.__init(); //globel init
    14. }
    15. /**
    16. * 初始化对象,创建iframe并绑定其window的resize
    17. *
    18. */
    19. ElementResize.prototype.__init = function () {
    20. var iframe = this.crateIElement();
    21. this.el.style.position = "relative";
    22. this.el.appendChild(iframe);
    23. this.bindEvent(iframe.contentWindow);
    24. };
    25. /**
    26. * 设置元素样式
    27. * @param {HTMLObject} el
    28. * @param {Object} styleJson
    29. */
    30. ElementResize.prototype.setStyle = function (el, styleJson) {
    31. if (!el) return;
    32. styleJson = styleJson || {
    33. opacity: 0,
    34. position: "absolute",
    35. left: 0,
    36. top: 0,
    37. width: "100%",
    38. height: "100%",
    39. "z-index": "-999",
    40. };
    41. var styleText = "";
    42. for (key in styleJson) {
    43. styleText += key + ":" + styleJson[key] + ";";
    44. }
    45. el.style.cssText = styleText;
    46. };
    47. /**
    48. * 创建元素
    49. * @param {Object} style
    50. */
    51. ElementResize.prototype.crateIElement = function (style) {
    52. var iframe = document.createElement("iframe");
    53. this.setStyle(iframe);
    54. return iframe;
    55. };
    56. /**
    57. * 绑定事件
    58. * @param {Object} el
    59. */
    60. ElementResize.prototype.bindEvent = function (el) {
    61. if (!el) return;
    62. var _self = this;
    63. el.addEventListener("resize", function () {
    64. _self.runQueue();
    65. },
    66. false
    67. );
    68. };
    69. /**
    70. * 运行队列
    71. */
    72. ElementResize.prototype.runQueue = function () {
    73. var queue = this.queue;
    74. for (var i = 0; i < queue.length; i++) {
    75. typeof queue[i] === "function" && queue[i].apply(this);
    76. }
    77. };
    78. /**
    79. * 监听
    80. * @param {Object} cb 回调函数
    81. */
    82. ElementResize.prototype.listen = function (cb) {
    83. if (typeof cb !== "function")
    84. throw new TypeError("cb is not a function!");
    85. this.queue.push(cb);
    86. };
    87. /**
    88. * 解除监听
    89. *
    90. */
    91. ElementResize.prototype.unListen = function () {
    92. this.queue = [];
    93. };
    94. self.ElementResize = ElementResize;
    95. })();

    该文件构建了一个ElementResize构造方法,通过实例化该构造方法创建出监听实例,将该文件引入文件,使用方法如下:

    1. html>
    2. <html>
    3. <head>
    4. <meta charset="utf-8" />
    5. <title>DIV尺寸监听title>
    6. <script src="./divResizeObserver.js">script>
    7. head>
    8. <body>
    9. <button onclick="listenResize()">监听变化button>
    10. <button onclick="unListenResize()">解除监听button>
    11. <button onclick="changeSize()">改变尺寸button>
    12. <div id="content">
    13. div尺寸变更监听
    14. div>
    15. <script type="text/javascript">
    16. var eleResize = new ElementResize("#content");
    17. //执行监听
    18. function listenResize(){
    19. eleResize.listen(function () {
    20. console.count("listener1触发");
    21. });
    22. eleResize.listen(function () {
    23. console.count('listener2触发');
    24. });
    25. }
    26. //监听调用
    27. listenResize();
    28. //解除监听
    29. function unListenResize(){
    30. eleResize.unListen();
    31. }
    32. //宽高变化
    33. function changeSize(){
    34. var el = document.querySelector("#content");
    35. el.style.width = Math.floor(Math.random() * 900) + "px";
    36. el.style.height = Math.floor(Math.random() * 500) + "px";
    37. }
    38. script>
    39. <style type="text/css">
    40. #content {
    41. background:blue;
    42. max-width: 100%;
    43. max-height: 100%;
    44. overflow: auto;
    45. text-align:center;
    46. }
    47. html,
    48. body {
    49. height: 100%;
    50. width: 100%;
    51. margin:0;
    52. }
    53. style>
    54. body>
    55. html>

    效果如下:

     方案2  ResizeObserver

        ResizeObserver 接口可以监听到 Element 的内容区域或 SVGElement的边界框改变。

    该对象提供三种方法:

    ResizeObserver.disconnect()https://developer.mozilla.org/zh-CN/docs/Web/API/ResizeObserver/disconnect

            取消和结束目标对象上所有对 ElementSVGElement 观察。

    ResizeObserver.observe()https://developer.mozilla.org/zh-CN/docs/Web/API/ResizeObserver/observe

            开始观察指定的 ElementSVGElement

    ResizeObserver.unobserve()https://developer.mozilla.org/zh-CN/docs/Web/API/ResizeObserver/unobserve

            结束观察指定的ElementSVGElement

    使用方式也很简单:

    1. html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
    6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    7. <title>Documenttitle>
    8. head>
    9. <body>
    10. <button onclick="change()">更改button>
    11. <div id="test" class="test" >
    12. div>
    13. <script>
    14. function change(){
    15. let el = document.querySelector('#test');
    16. // el.style.width =Math.floor(Math.random()* 1000) + 'px';
    17. el.style.height =Math.floor(Math.random() * 1000 ) + 'px';
    18. }
    19. window.onload = function(){
    20. // 尺寸监听
    21. const resizeObserver = new ResizeObserver(entries => {
    22. console.count("resize变化啦");
    23. });
    24. const someEl = document.querySelector('#test');
    25. resizeObserver.observe(someEl);
    26. }
    27. script>
    28. <style>
    29. .test{
    30. width:100%;
    31. height:100%;
    32. min-height:100px;
    33. background:red
    34. }
    35. style>
    36. body>
    37. html>

     效果:

             该对象的方法使用非常方便,缺点是浏览器兼容性不好:

            那是不是就不能使用了呢,我们可以使用一个github上的ResizeObserver Polyfill。

    安装:

    npm install resize-observer-polyfill --save-dev

     使用方式:

    1. import ResizeObserver from 'resize-observer-polyfill';
    2. const ro = new ResizeObserver((entries, observer) => {
    3. for (const entry of entries) {
    4. const {left, top, width, height} = entry.contentRect;
    5. console.log('Element:', entry.target);
    6. console.log(`Element's size: ${ width }px x ${ height }px`);
    7. console.log(`Element's paddings: ${ top }px ; ${ left }px`);
    8. }
    9. });
    10. ro.observe(document.body);

    最后,更多内容欢迎小伙伴关注:

  • 相关阅读:
    [HCTF 2018]WarmUp1
    设计模式 22 模板方法模式
    【无标题】
    使用docker搭建squid和ss5
    Java“牵手”微店商品列表数据,关键词搜索微店商品数据接口,微店API申请指南
    【Java】想进大厂?你应该知道的算法经典习题(链表)
    云函数cron-parser解析时区问题
    鲜花绿植学生网页设计模板 静态HTML鲜花学生网页作业成品 DIV CSS网上鲜花植物主题静态网页
    大数据-199 数据挖掘 机器学习理论 - 决策树 模型 决策与条件 香农熵计算
    docker-compose部署mysql
  • 原文地址:https://blog.csdn.net/u014399368/article/details/126411005