首页>前端教程>jQuery教程

自定义一个简单的jQuery插件,掌握套路!

虽然现在jQuery只在老项目中使用了,但是这个曾经辉煌一时,解决了很多浏览器兼容性问题,拯救了大部分程序员头发的库,还是非常伟大的,它的思想还值得学习。

这里分享一个自定义jQuery插件的小案例,以后遇到需要剥离出来的代码,就可以通过这种方式完成。

点击舞台产生随机的图形,可以自由配置几个参数。自定义插件的套路差不多就这样的。

点击图片试试……

16.jpg

核心代码:

    <div class="box">
        <!-- <div class="ball"></div> -->
    </div>
    <script src="js/jquery.js"></script>
    <script src="js/addBall.js"></script>
    <script>
        // 每次点击就添加一个元素在舞台上
        $('.box').on('click', function (e) {
            const num = getRandom(20, 100);
            // 调用自己写的方法,传递需要的参数
            $(this).addBall({
                width: num,
                height: num,
                borderRadius: `${getRandom(20, 50)}px`, // 需要带单位
                backgroundColor: `rgba(${getRandom(80,255)},${getRandom(80,255)},${getRandom(80,255)})`,
                // 鼠标点击的x和y坐标
                x: e.clientX,
                y: e.clientY
            });
        })
        function getRandom(min, max){
            return Math.floor(Math.random()*(max - min + 1) + min);
        }
    </script>
// addBall.js

;(function($){
    // 为jquery添加一个自己的方法
    $.fn.addBall = function (options) {
        // 默认参数
        const defaults = {
            width: 50,
            height: 50,
            borderRadius: '50%',
            backgroundColor: '#f60',
            // 谁调用这个函数,谁就是this
            x: Math.random()*$(this).width(),
            y: Math.random()*$(this).height(),
        }
        // 把用户的参数和默认的参数合并,当有冲突时,后面的覆盖前面的,最后返回前面参数对象.
        const result = $.extend(defaults, options);
        // console.log(result == defaults); // true

        const $Div = $(`<div class="ball" style = "width:${result.width}px;height:${result.height}px;border-radius:${result.borderRadius};left:${result.x - result.width / 2}px;top:${result.y - result.height / 2}px;position:absolute;background-color:${result.backgroundColor}"></div>`);

        $Div.appendTo($(this));
        $Div.on('click', function (e) {
            // 点击产生的形状时删除并阻止冒泡产生新的形状
            $(this).remove();
            e.stopPropagation();
        })
        // 返回调用该函数的对象,可以实现链式调用
        return $(this);
    }
})(jQuery);


点赞


0
保存到:

相关文章

发表评论:

◎请发表你卖萌撒娇或一针见血的评论,严禁小广告。

Top