前端控制超出n行后文本超出隐藏并添加title属性

 

<!--
 * @Description: 限制最大行数,超出显示...,在ie下超出隐藏
-->
<template>
  <div
    class="HtmlLineLimit"
    :style="{
      height: height || line * 1.5 + 0.25 + 'em',
    }"
  >
    <div
      ref="limitText"
      class="line_limit_body"
      :style="{
        WebkitLineClamp: line,
      }"
    >
      <slot></slot>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    line: {
      type: Number,
      default: 2,
    },
    height: String,
    // fontSize:{
    //     type:Number,
    //     default:14
    // }
  },
  data() {
    return {
      observer: null,
    };
  },
  mounted() {
    //元素超出隐藏时添加title
    this.setTitle();
    //   应对异步的数据,如组件是在获取到数据后加载可不加该监控
    try {
      let that = this;
      // 创建一个observer对象并指定回调函数
      this.observer = new MutationObserver(function (mutations) {
        mutations.forEach(function (mutation) {
          console.log(mutation);
        //   监听元素中子元素变化,config对应的配置为childList: true
          if (
            mutation.type === "childList" &&
            mutation.target === that.$refs.limitText
          ) {
            // console.log("元素innerHTML已经变化");
            that.setTitle();
          }
        //监听子元素的变化,如solt中只有文案变化无元素变化,监听获取的是text,所以要与text的父元素对比
          if (
            mutation.type === "characterData" &&
            mutation.target.parentElement === that.$refs.limitText
          ) {
            that.setTitle();
          }
        });
      });
      // 配置观察选项:
      const config = { childList: true, characterData: true, subtree: true };
      // 传入目标节点和观察选项到observer中
      this.observer.observe(this.$refs.limitText, config);
    } catch (error) {
      // console.log(error);
    }
  },
  beforeDestroy() {
    if (this.observer) {
      this.observer.disconnect();
      this.observer = null;
    }
  },
  methods: {
    setTitle() {
      // console.log(this.$refs.limitText.innerText);
      if (
        this.$refs.limitText &&
        this.$refs.limitText.offsetHeight < this.$refs.limitText.scrollHeight
      ) {
        // console.log(this.$refs.limitText.innerText);
        this.$refs.limitText.setAttribute(
          "title",
          this.$refs.limitText.innerText
        );
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.HtmlLineLimit {
  width: 100%;
  overflow: hidden;
}
.line_limit_body {
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  white-space: normal;
  word-break: break-all;
}
</style>

改方法是整合后自建的一个vue2组件

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值