jquery 扩展方法($.fn.extend/$.extend) 自定义插件 拖拽

文章目录

      • 扩展方法
        • 给jquery对象本身扩展方法 $.xxx
        • 给jquery Dom对象扩展方法 $(div).xxx
      • 自定义插件 拖拽

扩展方法

给jquery对象本身扩展方法 $.xxx

$.extend({
     
    lg(){
     
        console.log('扩展lg方法')
    }
})
// $.lg()

给jquery Dom对象扩展方法 $(div).xxx

$.fn.extend({
     
    domfun(){
     
        // $(this); 指向调用者 $(div)
        console.log('扩展domfun方法')
        return $(this)
    }
})


// 或者
$.fn.domfun2 = function(){
     
    // $(this); 指向调用者 $(div)
    console.log('扩展domfun方法')
    return $(this)
}
// $(div).domfun().domfun2

自定义插件 拖拽

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
    <style>
        div{
     
            width: 100px;
            height: 100px;
            background-color: aqua;
        }
    </style>
</head>
<body>
    <div>fff</div>
    <script>

        $.fn.dragGable = function(options={
     }){
     
            const defaultObj = {
     
                limit: false,
            }
            Object.assign(defaultObj, options)

            const {
     limit} = defaultObj
            const dom = $(this)

            // 修改元素定位
            dom.css({
     
                position:'absolute',
                top:0,
                left:0,
                cursor: 'move'
            })

            dom.mousedown(function(e){
     
                let startX = e.pageX -  dom.offset().left
                let startY = e.pageY -  dom.offset().top

                $(document).mousemove(function(ed){
     
                    let moveX = ed.pageX - startX
                    let moveY = ed.pageY - startY

                    // 边界限制
                    if(limit){
     
                        let rightBorder =  $(this).innerWidth() - dom.outerWidth()
                        let bottomBorder =  $(this).innerHeight() - dom.outerHeight()
                        moveX = moveX <= 0 ? 0 : moveX
                        moveX = moveX >= rightBorder ? rightBorder : moveX
                        moveY = moveY <= 0 ? 0 : moveY
                        moveY = moveY >= bottomBorder ? bottomBorder : moveY
                    }
                    dom.css({
     
                        left: moveX,
                        top: moveY
                    })
                })

                $(document).mouseup(function(){
     
                    $(this).off()
                })

                return false
            })
        }

        $('div').dragGable({
     
            limit: true, // 是否限制范围
        })
    </script>
</body>
</html>

你可能感兴趣的:(jquery)