收藏
回答

boundingClientRect微信小程序获取元素宽度引起内存占用问题

框架类型 问题类型 API/组件名称 终端类型 微信版本 基础库版本
小程序 Bug boundingClientRect 工具 6.5.3 3.10.3
Component({
  properties: {
    // 要显示的文本内容
    text: {
      type: String,
      value: '',
      observer: 'checkOverflow' // 当文本变化时重新检查是否溢出
    },
  },


  data: {
    isOverflow: false// 文本是否溢出
    showAll: false,    // 是否显示全部文本
    showPopup: false   // 是否显示弹窗
  },


  lifetimes: {
    // 组件布局完成后检查是否溢出
    ready() {
      this.checkOverflow();
    }
  },


  methods: {
    // 检查文本是否溢出容器
    checkOverflow() {
      const query = this.createSelectorQuery();
      
      // 获取测量文本的宽度
      query.select('.text-measure').boundingClientRect(measureRect => {
        console.log(measureRect.width)
        // 如果没有指定容器宽度,则获取容器实际宽度
          query.select('.text-container').boundingClientRect(containerRect => {
            if (containerRect && measureRect) {
              const isOverflow = measureRect.width > containerRect.width - 40// 减去"更多"按钮的大概宽度
              this.setData({ isOverflow });
            }
          }).exec();
      }).exec();
    },


    // 点击"更多"按钮
    onMoreTap() {
      this.setData({ showPopup: true });
    },


    // 点击弹窗背景关闭
    onMaskTap() {
      this.setData({ showPopup: false });
    },


    // 点击弹窗内容不关闭
    onContentTap() {
      // 空函数,用于阻止事件冒泡到mask
    },


    // 点击关闭按钮
    onCloseTap() {
      this.setData({ showPopup: false });
    }
  }
});





boundingClientRect 函数会一直执行,同时打印measureRect.width会一直打印


最后一次编辑于  2025-10-20
回答关注问题邀请回答
收藏

1 个回答

  • 智能回答 智能回答 本次回答由AI生成
    2025-10-20
    有用
登录 后发表内容