基于vue中对鼠标划过事件的处理方式详解

2018-09-22 01:09

阅读:608

  鼠标事件进行监听

  需求中,在一个table(组件)表中,对于其中一列(该列为图片列),当鼠标划过该列的某个单元格子(图片)时,需要展示出该单元格子对应的遮罩层

  翻阅了一些博客,发现好多都提到了mouse事件,如mouseover、mouseout、mouseenter、mouseleave,在之后我自己也通过这种方法进行了尝试。

   <template> <el-table :data=tableData stripe style=width: 100%> <el-table-column prop=pic label=图片 width=180> <template slot-scope=scope> <div slot=wrapper class=name-wrapper> <div class=img-mask @click=toShowDialog(props.row) :ref=mask + props.rowIndex>文字</div> <div @mouseover=changeMask(props.rowIndex) @mouseout=changeMask(props.rowIndex)> <img src=...> </div> </div> </template> </el-table-column> </el-table> </template> ... changeMask(index) { let vm = this; let mask = vm.$refs[mask + index]; if(mask.style.display == none) { mask.style.display = block; }else { mask.style.display = none; } }

  最后在查看结果中发现,在划过的时候是会触发鼠标事件,但是会出现闪动的清空,当鼠标一直放在该单元格上的时候,遮罩层也会消失和出现反复切换。为缓解这种情况,还对changeMask中的显示和隐藏进行setTimeout延时,结果并不理想,不推荐这样使用。

  CSS方式实现

  这种方法,只需要保留上面代码中的主体部分,不需要ref和mouse事件这些,主要是通过opacity去控制遮罩层的显示和隐藏的。具体的样式代码如下:

   .wrapper { position: relative; .img-mask { position: absolute; background: rgba(0, 0, 0, 0.5); z-index: 10; //设置left、right、top、bottom的原因是使得遮罩层上的文字显示在该层的最中间 left: 0; right: 0; top: 0; bottom: 0; //透明度为0,则就是不可见 opacity: 0; } &:hover { .img-mask { opacity: 1; } } }

  这种方法达到了预期的效果,体验也很好,推荐使用。

  table中动态ref

  首先,这部分并不是针对遮罩层显示隐藏的,而是处理表格中某一列或者很多单元格添加ref的。这个其实在第一种方法中就已经也出来了,现在做下总结。

  :ref=mask + props.rowIndex这种方法对例如表格这样一列中的每个单元格都对应着一个附加的东西,而这些东西的位置又是不同的,可以实现对每个单元格进行ref绑定,在事件处理函数中,通过传递props.rowIndex得到下标,最终通过this.$ref[mask + props.rowIndex]得到对应的元素,然后对其css进行相关控制(只是举例)。

  拓展知识:vue鼠标划过移入移出触发函数介绍

  如下所示:

   <ul>> <li class= v-on:mouseover=changeActive($event) v-on:mouseout=removeActive($event)></li> </ul> methods:{ // 鼠标移入加入class changeActive($event){ $event.currentTarget.className=active; }, removeActive($event){ $event.currentTarget.className=; } }

  以上这篇基于vue中对鼠标划过事件的处理方式详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。


评论


亲,登录后才可以留言!