How do I detect the inherited background-color of an element using jQuery/JS?

后端 未结 6 917
礼貌的吻别
礼貌的吻别 2020-11-30 11:40

Using jQuery (or just JavaScript), how do I detect the inherited background-color of an element?

For example:

6条回答
  •  清歌不尽
    2020-11-30 12:01

    Here's an elegant way of solving this problem (sorry, I prefer CoffeeScript). It starts from self, but you always can just use $el.parents().each ->.

    findClosestBackgroundColor = ($el) ->
        background = 'white'
        $.merge($el, $el.parents()).each ->
          bg = $(this).css('background-color')
          if bg isnt 'transparent' and !/rgba/.test(bg)
            background = bg
            return false
        background
    

    DEMO: Use coffeescript.org to compile this to javascript and run this in a console on any page that has jQuery included.

提交回复
热议问题