Tạo hiệu ứng ripple material (gợn sóng) cho button khi click

Khôi Ròm - tháng 7 05, 2018 - Blogspot, Thủ thuật blogspot
Tạo hiệu ứng ripple material (gợn sóng) cho button khi click

Trong bài viết hôm nay, mình sẽ mang đến cho mọi người 1 button với hiệu ứng ripple material khi click. Thủ thuật này sử dụng Jquery nhé, cân nhắc có nên dùng hay không nhé.

Cách thực hiện

Bước 1: Truy cập blogger.com > chủ đề > chỉnh sửa HTML
Bước 2: Dán đoạn css nhỏ dưới này lên trên
]]></b:skin>
button {
    display: inline-block;
    cursor: pointer;
    border: none;
    margin: 2rem;
    padding: 0.8rem 1rem;
    color: #f3f3f3;
    background-color: #4285f4;
    transition: 160ms ease-out;
    box-shadow: 0 2px 4px rgba(0,0,0,.26);
}
button:hover {
    box-shadow: 0 5px 6px rgba(0,0,0,.3);
    background-color: #2e69cc;
}

.ripple {
    background-color: rgba(245, 245, 245, 0.54);
    border-radius: 100%;
    position: absolute;
    transform: scale(0);
    animation: makeRipple 600ms linear;
}

.positionRipple {
    position: absolute;
    width: 100%; height: 100%;
    background-color: transparent;
    top: 0; left: 0;
}

@-webkit-keyframes makeRipple {
    to {transform: scale(2); opacity: 0;}
}
Bước 3: Dán đoạn jquery này lên trên thẻ đóng
</body>
<script>
//<![CDATA[
document.addEventListener('DOMContentLoaded', function(){
    var btn = document.querySelectorAll('button');
    
    function ripple(e) {
        let crl = document.createElement('div'), pr = document.createElement('div');
        crl.classList.add('ripple');
        pr.classList.add('positionRipple');
        let d = Math.max(this.clientWidth, this.clientHeight);
        crl.style.width = crl.style.height = d + 'px';
        crl.style.top = e.offsetY - d/2 + 'px'; 
        crl.style.left = e.offsetX - d/2 + 'px'; 
        this.appendChild(crl);
        this.appendChild(pr);
    }
    
    for(let i = 0; i<btn.length; i++) {
        btn[i].style.position = "relative";
        btn[i].style.overflow = "hidden";
        btn[i].onclick = ripple;
        btn[i].addEventListener('animationend', function(){
            let crl = this.querySelector('.ripple'), 
            pr = this.querySelector('.positionRipple');
            this.removeChild(crl);
            this.removeChild(pr);
        });
    }
},false);
//]]></script>

Cách sử dụng

Chèn đoạn code này vào bất kì nơi nào bạn muốn, chú ý xóa các css button trùng lặp nhé
<button><a href='#'>Ripple Effect</a></button>

Tổng kết

Với một chút css và jquery, chúng ta đã tạo ra hiệu ứng ripple cho button rồi phải không. Chúc các bạn thành công!. Đừng quên để lại bình luận nhé