微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何从插件扩展jQuery.css

我写了一个非常简单的插件,允许我使用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>')

解决方法

这似乎对我有用: http://jsfiddle.net/frfdj/
(function($) {
    var _css = $.fn.css; // store method being overridden
    $.fn.css = function(opts) {
        $.each(['background',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)

原文地址:https://www.jb51.cc/jquery/178092.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐