小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
前文学习了 Vue
的自定义指令之基础篇, 先要打好基础. 及自定义指令-UI权限验证. 今天来学习 Vue小知识-常用指令(二) 点击按钮水波效果. 好多网站都有这个效果!
Vue 自定义指令: 点击按钮水波效果
比方说在点击按钮时, 从点击处像水波纹一样向周围扩散开来, 显示水波效果.
自定义指令模块
目录位置: src/directives/waves.js
// 引入样式效果,
import './waves.css'
export default {
bind(el, binding) {
el.addEventListener(
'click',
(e) => {
const customOptions = Object.assign({}, binding.value)
const opts = Object.assign(
{
ele: el, // 要显示波纹的元素 挂载元素
// hit: 扩散类型: 从点击的位置处扩散
type: 'hit', // 以center 为中心点向外扩展
color: 'rgba(0, 0, 0, 0.15)', // 波纹显示颜色: 这里是浅灰, 可定制你觉得好看的
},
customOptions
)
const target = opts.ele
if (target) {
target.style.position = 'relative'
target.style.overflow = 'hidden'
const rect = target.getBoundingClientRect()
let ripple = target.querySelector('.waves-ripple')
if (!ripple) {
ripple = document.createElement('span')
ripple.className = 'waves-ripple'
ripple.style.height = ripple.style.width = Math.max(rect.width, rect.height) + 'px'
target.appendChild(ripple)
} else {
ripple.className = 'waves-ripple'
}
switch (opts.type) {
case 'center':
ripple.style.top = rect.height / 2 - ripple.offsetHeight / 2 + 'px'
ripple.style.left = rect.width / 2 - ripple.offsetWidth / 2 + 'px'
break
default:
ripple.style.top =
(e.pageY -
rect.top -
ripple.offsetHeight / 2 -
document.documentElement.scrollTop || document.body.scrollTop) + 'px'
ripple.style.left =
(e.pageX -
rect.left -
ripple.offsetWidth / 2 -
document.documentElement.scrollLeft || document.body.scrollLeft) + 'px'
}
ripple.style.backgroundColor = opts.color
ripple.className = 'waves-ripple z-active'
return false
}
},
false
)
},
}
使用方式:
使用也很简单, 在目标标签上使用 v-waves
, 在点击此元素时就会显示出来效果:
<button v-waves style="width: 200px;height: 100px">点击此按钮显示水波纹, 通过指令 v-waves 显示</button>