點按觸發水波紋效果
阿新 • • 發佈:2019-01-09
前一段時間(也可能很久了吧),網易客戶端看新聞時發現,手指觸按每條新聞時會有水波紋效果,覺得好神奇,當時就好奇這個效果怎麼做的;今天工作空閒,嘗試找了一下,然後實戰成功。
程式碼如下:
html:
js:<pre name="code" class="html"><!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>ripple</title> <link rel="stylesheet" type="text/css" href="index.css"> <script type="text/javascript" src="jquery-1.9.1.min.js"></script> </head> <body> <div id="wrap"> <h1>Android L Ripple Effect</h1> <div id="main"> <button>BUTTON</button> <button>BUTTON</button> <button>BUTTON</button> <button>BUTTON</button> </div> </div> </body> </html>
css:<script type="text/javascript"> $('body').on('click',function(e){ var offset = $(this).offset(); var target = e.target; if (target.tagName.toLowerCase() !== 'button') return false; //非button 則阻止 var rect = target.getBoundingClientRect(); var x = e.pageX; var y = e.pageY; var ripple = $('<span class="ripple"></span>'); ripple.css('width',Math.max(rect.width,rect.height)); ripple.css('height',Math.max(rect.width,rect.height)); ripple.appendTo(target).css({ left: (x - offset.left - rect.left - ripple.width()/2) + 'px', top : (y - offset.left - rect.top - ripple.height()/2) + 'px' }); }) </script>
body { margin: 0; padding: 0; } #wrap { position: absolute; width: 100%; height: 100%; display: flex; flex-flow: column; justify-content: center; align-items: center; } h1 { display: flex; margin: 0; padding: 0; align-items: center; flex: 2; } #main { flex: 5; } button { position: relative; display: block; width: 13em; height: 3em; margin: 2em; border: none; outline: none; letter-spacing: .2em; font-weight: bold; background: #dfdfdf; cursor: pointer; overflow: hidden; user-select: none; border-radius: 2px; } button:nth-child(2) { color: #fff; background: #4285f4; } button:nth-child(3) { color: #fff; background: #00bad2; } button:nth-child(4) { color: #fff; background: #ff8a80; } .ripple { position: absolute; background: rgba(0,0,0,.15); border-radius: 100%; transform: scale(0); pointer-events: none; animation: ripple .75s ease-out; } .ripple.show { animation: ripple .75s ease-out; } @keyframes ripple { to { transform: scale(2); opacity: 0; } }
參考文章:http://www.tuicool.com/articles/jieuYn