jquery - 如何从插件扩展 jQuery.css

标签 jquery css plugins jquery-animate

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

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

如何扩展 $.fn.css 函数的功能,是否有任何需要注意的陷阱?

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

fiddle :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>')

最佳答案

这似乎对我有用: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)

关于jquery - 如何从插件扩展 jQuery.css,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7446123/

相关文章:

javascript - 限制 contenteditable div 中存储在数据库中的字符数

javascript - JQuery AJAX COR 错误

.net - ASP.NET MVC/jQuery : Inplace Editing

jquery - 在所有标签上应用占位符?

css - 我可以仅使用 CSS 使悬停时页面的其余部分变暗吗?

css - 如何构建 CSS 类?按实体还是按方面?

html - 在电子邮件中显示 html

javascript - 如果不使用 XMLHttpRequest,我们如何使用 JavaScript 跨域获取网页?有没有可以做到这一点的插件?

javascript - 如何在运行时添加的对象上执行 Jquery 插件

php - 如何将多个 PHP 变量传递给 jQuery 函数?