可多次使用的jq弹出层特效

暂无标签

一个jq代码,只要按钮和弹出层对应,可在同页面多次使用。
html代码:
按钮

<a href="javascript:;" data-show-layer="hw-layer-reward" role="button" class="show-layer btn btn-block btn-default"><i class="fa fa-qrcode"></i> <span>打赏支持</span></a>

data-show-layer="hw-layer-自定义"
弹出层

<div class="hw-overlay" id="hw-layer-reward">
        <div class="hw-layer-wrap modal-header">
                <div class="index-sections panel panel-default" style="box-shadow: none;">
                        <div class="panel-heading">打赏<button type="button" class="close hwLayer-close" aria-label="Close"><span aria-hidden="true">×</span></button></div>
                        <div class="modal-header">
                <div class="message">
                    <div class="user-info"><img class="media-object avatar-48" src="uc_server/avatar.php?uid={$ua['guid']}&size=middle" alt="{$ua['username']}"></div>
                    <p><i class="fa fa-quote-left pull-left"></i>如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!<i class="fa fa-quote-right pull-right"></i></p>
                </div>
            </div>
            <div class="modal-body clearfix">
                <div class="reward-image"><img src=""/></div>
                <div class="reward-image"><img src=""/></div>
            </div>
        </div>
</div>
</div>

<div class="hw-overlay" id="hw-layer-自定义">自定义内容要与触发按钮相同。

jq代码

$(function(){
        //展示层
        function showLayer(id){
                var layer = $('#'+id),
                        layerwrap = layer.find('.hw-layer-wrap');
                layer.fadeIn();
                //屏幕居中
                layerwrap.css({
                        'margin-top': -layerwrap.outerHeight()/2
                });
        }
        //隐藏层
        function hideLayer(){
                $('.hw-overlay').fadeOut();
        }
        $('.hwLayer-ok,.hwLayer-cancel,.hwLayer-close').on('click', function() {
                hideLayer();
        });
        //触发弹出层
        $('.show-layer').on('click',  function() {        
                var layerid = $(this).data('show-layer');
                showLayer(layerid);
        });
        //点击或者触控弹出层外的半透明遮罩层,关闭弹出层
        $('.hw-overlay').on('click',  function(event) {
                if (event.target == this){
                        hideLayer();
                }
        });
        //按ESC键关闭弹出层
        $(document).keyup(function(event) {
                if (event.keyCode == 27) {
                        hideLayer();
                }
        });
});