当前位置:   article > 正文

用ResizeObserver对象监听div的尺寸(宽度高度)发生变化_监听div高度发生变化

监听div高度发生变化

代码片段

  1. <template>
  2. <div :class="$options.name"></div>
  3. </template>
  4. <script>
  5. export default {
  6. mounted() {
  7. this.resizeObserverThisEl();
  8. },
  9. destroyed() {
  10. this.resizeObserver.unobserve(this.$el); // 停止监听元素的尺寸变化
  11. this.resizeObserver.disconnect(); // 如果不再需要该 ResizeObserver 实例,可以停止所有观察并清理资源
  12. },
  13. methods: {
  14. resizeObserverThisEl(d) {
  15. const div = this.$el; //监听组件自身
  16. this.resizeObserver = new ResizeObserver((entries) => {
  17. for (let entry of entries) {
  18. const width = entry.contentRect.width;
  19. const height = entry.contentRect.height;
  20. console.log(`Size: Width = ${width}, Height = ${height}`);
  21. }
  22. //当尺寸发生变化的时候触发一些行为…
  23. });
  24. this.resizeObserver.observe(div);
  25. },
  26. },
  27. };
  28. </script>

详细解读不用addEventListener(‘resize‘, this.resize),用新的Web API ResizeObserver监听DIV元素尺寸的变化_监听div大小变化-CSDN博客文章浏览阅读274次。但有第三方的polyfill方案,可以支持到 FF44+,IE9+,Edge 10+ ,Safari 11+ ,兼容方案是通过 MutationObserver API 实现的,通过监听 dom 的变化并加以判断,至此主流浏览器均可运行。响应式设计指的是根据屏幕视口尺寸的不同,对 Web 页面的布局、外观进行调整,以便更加有效地进行信息的展示。响应式设计如今也成为 web 应用的基本需求,而现在很多 web 应用都已经组件化,这意味着我们如果想要实现响应式的应用,那么我们也需要有某种方式监听。_监听div大小变化https://blog.csdn.net/qq_37860634/article/details/133160598

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号