vue 不固定宽度文字超出显示...鼠标移入浮层显示全文,模拟title浮层方法

先说说思路:

1、不固定宽度文字超出显示...,用的css3     overflow: hidden;text-overflow:ellipsis;white-space: nowrap;

2、文字超出的地方鼠标移入显示全文。我的思路是这样的,先获取容器的宽度、字号、全部文字,把获取的全部文字放到一个动态生成的span中,给span设置字号为容器的字号,再获取出来span的长度,容器宽度小于span宽度的情况下会显示浮层展示全文。

3、事件分为鼠标移入,移动,移出三个步骤。这里鼠标移入我用的是mouseover

下面上代码干货

//文字超出部分显示...鼠标经过浮层显示全部文字
export const mouseover = ( $event ) => {
alert ( 1 )
let dom = $event . target ,
style = window . getComputedStyle ? window . getComputedStyle ( dom , '' ) : dom . currentStyle ,
width = dom . clientWidth , //容器宽度
paddingRight = style . paddingRight , //右padding
paddingLeft = style . paddingLeft , //左padding
marginLeft = style . marginLeft , //左margin
marginRight = style . marginRight , //左margin
boxWidth = width - parseInt ( paddingRight ) - parseInt ( paddingLeft ) - parseInt ( marginLeft ) - parseInt ( marginRight ),
fontSize = style . fontSize ,
text = dom . innerHTML ,
span = document . createElement ( "span" ),
left = $event . clientX ,
top = $event . clientY ;
span . style . cssText = `font-size:12px;height:0;overflow:hidden;` ;
span . setAttribute ( 'id' , 'span' );
document . body . appendChild ( span );
document . querySelector ( '#span' ). innerHTML = text ;
let spanWidth = span . offsetWidth ;
document . body . removeChild ( span );
if ( spanWidth > boxWidth ) {
let bgObj = document . createElement ( "div" );
bgObj . style . cssText = `position:absolute;top: ${ top + 5 } px;left: ${ left } px;color:#fff;background:#333;max-width:400px;border-radius:5px;padding:10px;display:inline-block;font-size:12px;z-index:9999` ;
bgObj . setAttribute ( 'id' , 'bgObj' );
document . body . appendChild ( bgObj );
document . querySelector ( '#bgObj' ). innerHTML = text ;
}
}
//鼠标移出浮层消失
export const mouseout = ( $event ) => {
let bgObj = document . querySelector ( '#bgObj' );
if ( bgObj ) {
document . body . removeChild ( bgObj );
}
}
//鼠标移动浮层移动
export const mousemove = ( $event ) => {
let left = $event . clientX ,
top = $event . clientY ,
bgObj = document . querySelector ( '#bgObj' );
if ( bgObj ) {
bgObj . style . top = ( top + 10 ) + 'px' ,
bgObj . style . left = left + 'px' ;
}
}

组件中是这样用的

< li v-for = "(company,index) in companys" : key = "index" @mouseover="mouseover()" @mouseout="mouseout()"
@mousemove ="mousemove()"
>
{{company.name}} li >

当然,mouseover,mouseout,mousemove这三个方法我是放在了公共文件中,哪里用哪里引用就可以了

纯属技术分享,哪里有不完善的地方还请大家多多指教

你可能感兴趣的:(Vue.js)