如何判断一个 行 div 内文字是否溢出?

老生常谈的问题了,最近在项目中遇到了实际需求

当一个 div中的文字溢出的时候 就展示 true 否则就展示 false

附上 在线测试地址

https://codepen.io/firstblood...

阅读 3.2k
1 个回答
<!-- Use preprocessors via the lang attribute! e.g. <template lang="pug"> -->
<template>
  <div id="app">
    <div ref="text" class="text">{{message}}</div>
    <div>是否溢出: {{isOverflow}}</div>
    <button @click="change">切换文字</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      isOverflow: true,
      message: '我的的确确溢出了吧'
    };
  },
  methods: {
    change() {
      this.message = this.message==='我的的确确溢出了吧'?'我没有溢出':'我的的确确溢出了吧';
      this.$nextTick(() => {
        var el = this.$refs.text;
        this.isOverflow = el && el.scrollWidth > el.offsetWidth;
      })
    }
  }
};
</script>

<!-- Use preprocessors via the lang attribute! e.g. <style lang="scss"> -->
<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}

  .text{
    border:1px solid red;
    max-width:120px;
    display:inline-block;
    overflow:hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
</style>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题