js 彈窗彈出+關閉+拖動效果

需求
  1. 打開時,從右下角彈出
  2. 關閉時,從右下角收回
  3. 拖動效果
技術點
  1. jquery animate() 方法
  2. draggabilly插件
效果預覽 https://stavinli.github.io/dialog_animate/
代碼
  • html
<span class="tip">消息通知</span>
<div class="dialog">
    <h3>彈窗標題 <span class="close">關閉</span></h3>
</div>
  • javascript
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/draggabilly/2.3.0/draggabilly.pkgd.min.js"></script>
<script>
    var thisDialog = $(".dialog")
    thisDialog.draggabilly()
    $(".tip").on("click", function() {
        thisDialog.hasClass("active") ? hideDialog() : showDialog()
    })
    $(".close").on("click", hideDialog)

    function showDialog() {
        var { left, top } = thisDialog.data()
        thisDialog.animate({
            left: typeof(left) != "undefined" ? left : (window.innerWidth - thisDialog.width()) / 2,
            top: typeof(top) != "undefined" ? top : (window.innerHeight - thisDialog.height()) / 2,
        }).addClass("active")
    }

    function hideDialog() {
        var { left, top } = thisDialog.position()
        thisDialog.data({
            left: left,
            top: top
        }).animate({
            left: "100%",
            top: "100%",
        }).removeClass("active")
    }
</script>
  • css
<style>
    span.tip {
        position: fixed;
        bottom: 0;
        right: 0;
        display: inline-block;
        width: 100px;
        height: 50px;
        text-align: center;
        line-height: 50px;
        color: #46a6fe;
        border: 1px solid #46a6fe;
        border-radius: 4px;
        cursor: pointer;
    }

    .dialog {
        position: fixed;
        top: 100%;
        left: 100%;
        width: 500px;
        height: 300px;
        z-index: 9;
        box-shadow: 0px 0px 18px rgba(0, 0, 0, .3);
        background: #fff;
    }

    .dialog h3 {
        margin: 0;
        padding: 0 20px;
        line-height: 42px;
        font-weight: normal;
        font-size: 16px;
        border-bottom: 1px solid #999;
    }

    .dialog h3 span {
        float: right;
        color: #f00;
        font-size: 12px;
        cursor: pointer;
    }
</style>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章