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

后端 未结 6 920
礼貌的吻别
礼貌的吻别 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:17

    Here's the answer for people who hate browser inconsistency.

    As explained, you need to test if this element has a transparent background, then if it does, walk through the DOM until you find a parent with background-color set - but that means testing whatever string each browser chooses to return.

    Firefox, IE and others return transparent, Chrome/safari/webkit browsers etc return rgba(0, 0, 0, 0)... and I personally don't trust that there won't be some other exception out there somewhere, now or in the future.

    If you don't like the idea of trusting a string given to you by a browser (and you shouldn't), you don't have to: just test against the background-color of an empty element.

    Here's a JSBIN example of it in action. (to test on old IE, remove 'edit' from URL)


    Usage: Plonk this code somewhere (it works as a jQuery plugin)...

    (function($) {
      // Get this browser's take on no fill
      // Must be appended else Chrome etc return 'initial'
      var $temp = $('
    ').appendTo('body'); var transparent = $temp.css('backgroundColor'); $temp.remove(); jQuery.fn.bkgcolor = function( fallback ) { function test( $elem ) { if ( $elem.css('backgroundColor') == transparent ) { return !$elem.is('body') ? test( $elem.parent() ) : fallback || transparent ; } else { return $elem.css('backgroundColor'); } } return test( $(this) ); }; })(jQuery);

    ...then you can get the 'inherited' background colour of any element like this:

    var backgroundColor = $('#someelement').bkgcolor();
    

    Or if you want a fallback to be applied instead of 'transparent' if no background-color is set here or anywhere behind this element (e.g. for matching overlays), send as an argument:

    var backgroundColor = $('#someelement').bkgcolor('#ffffff');
    

提交回复
热议问题