当前位置: 移动技术网 > IT编程>网页制作>CSS > 判断文本是否溢出/hover显示全部

判断文本是否溢出/hover显示全部

2018年11月09日  | 移动技术网IT编程  | 我要评论

大富翁4fun,公务员礼仪培训,车辆痕迹鉴定

前言

在工作中我们经常会遇到,文字过多,需要用省略号,并且鼠标hover的时候 还需要 显示全部的文字的需求。

正文

  1. 文字过多需要用省略号的实现:上代码啦
    .ellipsis {
          width: 100%;
          text-overflow: ellipsis;
          overflow: hidden;
          white-space: nowrap;
         display: inline-block //块级标签不需要
    }

     

  2.  如何得知这个是否溢出呢?关键词:clientwidth 和scrollwidth: 代码奉上:

    // 我是在react中实现
    
     componentdidmount () { // 在did mount 中判断是否溢出
        const node = this.ref.current  // 判断的dom节点,使用ref
        const clientwidth = node.clientwidth
        const scrollwidth = node.scrollwidth
        if (clientwidth < scrollwidth) {
          this.setstate({    // 把是否溢出的状态存在state中,之后从state中拿值使用
            overflow: true    
          })
        }
      }  // 在普通js中实现,方法一样,取到dom,判断clientwidth 和scrollwidth
  3. 判断完溢出,一般会需要处理,我这里的需求是hover时候再显示全部。方法两种,第一,使用伪类,第二,包裹一个标签,该标签hover时候显示。

     重点坑: 有省略号的标签,我们使用了overflow:hidden来实现了,那么这个就是一个bfc,hover时候显示的提示框,超出bfc的就显示不了了。。。

    方法一 : 伪类实现:代码上html

<span classname={`${styles.detail} ${styles.ellipsis}`} ref={this.departmentref} data-customer={overflow ? department : null}>{department}</span>

// 关注data-customer 属性,这个属性在有溢出时候赋值,无溢出时候为null。  还记得ref的作用不?就是第二步中确定是否溢出用的。
.ellipsis { // 第一步溢出的代码
          display: inline-block;  
          text-overflow: ellipsis;
          white-space: nowrap;
          overflow: hidden;
          width: 255px;
}
.ellipsis[data-customer]:hover::after { // 关键代码,伪类实现
          content: attr(data-customer);
          position: absolute;
          background: #f2f2f2;
          border: 1px solid #e5e5e5;
          box-shadow: 0 2px 4px 0 rgba(56,62,71,0.10);
          border-radius: 2px;
          padding: 2px 6px;
          font-size: 13px;
          color: #202332;
          top:106px; // 设置位置
          left: 10px; // 设置位置
          max-width: 90%;
          word-break: break-word; // 如果一个单词太长,则截断  css 属性 word-break 指定了怎样在单词内断行。
          white-space: normal;// 可以换行  white-space css 属性是用来设置如何处理元素中的空白。
}
            

 

    方法二:在hover标签a 内部再包裹一个标签b,b标签在hovera时显示。代码走你

<span ref={this.ref} style={{display: 'inline-block'}} classname={overflow ? 'overflowtext' : ''}>
{tabletitle} {overflow ? (<span classname='overflowspan'>{tabletitle}</span>) : null} </span> // 关键代码是那个三元~

 

.overflow{
   position: relative
}
.overflow .overflowspan {
    display: none
}

.overflow:hover .overflowspan{
   display: block;
   position: absolute;
   top: 10px;
left: 0px;
}

参考链接: https://stackoverflow.com/questions/2011142/how-to-change-the-style-of-the-title-attribute-inside-an-anchor-tag

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网