2017-03-03 7 views
2

透明でない背景色を持つ最も近い親を見つけようとします。親の背景色が透明でないことを確認

最初のコードは動作しますが、親が見つかりますが、色は透明です。

bg = (e.parentsUntil($(this).has().css("background-color"))).css("background-color"); 

だから私はこれで苦労:マイナーな問題があります

bg = (e.parentsUntil($(this).has().css("background-color") <> 'transparent').css("background-color"); 

、そのクロムはRGBA(0,0,0,0)と透明定義するが、これは、またはステートメントで可能でなければなりませんすぐに最初のハードルが取られます。

+0

['.parentsUntil()'](https://api.jquery.com/parentsUntil/)と['.has()'](https:// api)のドキュメントを実際に見てください。 .jquery.com/has /) – Andreas

+0

@Andreas私はそうしました。なぜ最初のコードが機能するのか...しかし、透明を排除する方法はありません。 – ratmalwer

+0

'.parentsUntil()'にセレクタまたは要素が必要です。 '.has()'はセレクタまたは要素を期待するので、 '$(this).has()'は空の集合を返します。 '.css(" background-color ")'が空集合で実行されると 'undefined'が返されます。したがって、すべての親を ''([fiddle](https://jsfiddle.net/tf5e0und/))まで返す 'e.parentsUntil(undefined) 'を呼び出しています – Andreas

答えて

2

興味深い質問!
これを行う方法が見つかりました。 ChromeとOperaのについては

、あなたは計算値rgba(0,0,0,0)の代わりtransparentをチェックする必要があります。

FirefoxとInternet Explorerの場合は、transparentを確認する必要があります。

以下のスニペットでは、透明でない(灰色の背景)divに赤い枠線が追加されています。
透明なものに青色の境界線が追加されています...あなたが見るだけのためです。
;)

$(".test").click(function(e){ 
 
    
 
    var parents = $(e.target).parents("div"); 
 
    parents.each(function(i){ 
 
    console.log("element #"+i); 
 
    console.log("Background: "+$(this).css('background')); 
 
    console.log("Background-color: "+$(this).css('background-color')); 
 

 
    // Chrome & Opera 
 
    if($(this).css('background-color').indexOf('rgba(0, 0, 0, 0)') == 0 
 
     // Firefox & Internet Explorer 
 
     || $(this).css('background-color').indexOf('transparent') == 0){ 
 

 
     $(this).css({"border":"2px solid blue"}); 
 
     console.log("Setting border to blue.\n\n"); 
 
    }else{ 
 
     $(this).css({"border":"2px solid red"}); 
 
     console.log("Setting border to red.\n\n"); 
 
    } 
 
    }); 
 
    console.log("Red border means NOT transparent."); 
 
});
.one{ 
 
    background:grey; 
 
    height:200px; 
 
    padding:40px; 
 
} 
 
.two{ 
 
    background:transparent; 
 
    height:200px; 
 
    padding:40px; 
 
} 
 
.three{ 
 
    background:transparent; 
 
    height:200px; 
 
    padding:40px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 

 
<div class="one"> 
 
    <div class="two"> 
 
    <div class="three"> 
 
     <span class="test">Hello - click me!</span> 
 
    </div> 
 
    </div> 
 
</div>

これは、完全なページモードでそれをチェックするのが最善かもしれません。
これを他のブラウザでテストするには、this CodePenを使用してください。

+1

私によく見えます。ところで、Firefoxではrgba(0,0,0,0)の代わりに 'transparent'が必要です。私はちょうどそれにぶつかる:-) Ok。クロムのために... – ratmalwer

+0

ありがとう!私はこれもFirefox上で動作するように編集しました。 –

+0

私はインターネットExploderのための解決策を見つけようとしています... –

関連する問題