2017-03-03 69 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'。所以你打電話給'e.parentsUntil(undefined)',它返回所有的父母,包括''([fiddle](https://jsfiddle.net/tf5e0und/)) – 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)。我只是碰到它:-)好吧。對於Chrome ... – ratmalwer

+0

謝謝!我爲此編輯也是在Firefox上工作。 –

+0

我試圖找到一個解決方案,因爲Internet Exploder不服從... –