<!--
* @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组件