【问题标题】:How to extend jQuery.css from plugin如何从插件扩展 jQuery.css
【发布时间】:2011-11-18 18:07:15
【问题描述】:

我编写了一个非常简单的插件,它允许我使用 0xffccaa 格式的 css 颜色而不是 '#ffccaa'(主要是为了避免写引号 - 但也可以通过简单地将颜色添加为整数来轻松修改颜色)。

我以$().xcss({}) 实现,但更愿意只使用$().css({})

如何扩展$.fn.css 函数的功能,有什么需要注意的陷阱吗?

另外,我想我也想为$.animate 做同样的事情。

小提琴:http://jsfiddle.net/hB4R8/

// pugin wrapper
(function($){ $.fn.xcss = function(opts){
    // loop through css color properties 
    $.each(['background', 'backgroundColor','background-color', 'color', 'borderColor','border-color'],function(i,v){
        // if set as number (will be integer - not hex at this point)
        // convert the value to `#ffccaa` format (adds padding if needed)
        if(typeof opts[v] === 'number')
            opts[v] = ('00000'+opts[v].toString(16)).replace(/.*([a-f\d]{6})$/,'#$1')
    })
    // run css funciton with modified options
    this.css(opts)
    // allow chaining
    return this
} })(jQuery)

// test the plugin
$('body').xcss({
    'background-color': 0xffccFF,
    color: 0xccffcc,
    border: '3px solid red',
    borderColor:0x0ccaa,
    padding:50
}).html('<h1>This should be a funny color</h1>')

【问题讨论】:

    标签: jquery css plugins jquery-animate


    【解决方案1】:

    这似乎对我有用:http://jsfiddle.net/frfdj/

    (function($) {
        var _css = $.fn.css; // store method being overridden
        $.fn.css = function(opts) {
            $.each(['background', 'backgroundColor', 'background-color', 'color', 'borderColor', 'border-color'], function(i, v) {
                if (typeof opts[v] === 'number') opts[v] = ('00000' + opts[v].toString(16)).replace(/.*([a-f\d]{6})$/, '#$1')
            })
            return _css.apply(this, [opts]); // call original method
        }
    })(jQuery)
    

    【讨论】:

    • 效果很好。我以为我在发布问题之前尝试过这个,但是当我将 $.fn.css 存储在一个变量中时,它只是存储了一个引用——它变成了对被覆盖函数的引用。我打电话给this._css(opts),但遇到了错误。我不完全理解 apply 发生了什么,但它很好用 - 非常感谢。
    • 恐怕还不够接近,但感谢您的客气话。很高兴你解决了你的问题。
    【解决方案2】:

    https://github.com/aheckmann/jquery.hook/blob/master/jquery.hook.js

    根据这个为任意函数创建钩子的代码,你可以在调用原始函数之前用一个你想要的方法覆盖 $.fn.css。

    【讨论】:

    • 一个非常有趣的答案/功能。我有两个问题... 1.是否需要您使用选择器,所以我使用* 选择页面上的所有对象,效率低下但更重要的是 2.它只对页面上已经存在的元素进行操作,而不是之后动态创建的元素。以下是我用来让它解决这些限制的代码的链接:gist。感谢您提供有趣的链接和有趣的答案。
    猜你喜欢
    • 1970-01-01
    • 2012-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-18
    • 2016-09-04
    • 1970-01-01
    相关资源
    最近更新 更多