我试图找到背景颜色不透明的最近的父节点。
第一个代码有效,它找到了父级,但那里的颜色是透明的。
bg = (e.parentsUntil($(this).has().css("background-color"))).css("background-color");
所以我为此而挣扎:
bg = (e.parentsUntil($(this).has().css("background-color") <> 'transparent' ).css("background-color");
有一个小问题,即 chrome 使用 rgba(0,0,0,0) 定义透明,但这应该可以通过 or 语句在第一个障碍解决后立即实现。
有趣的问题!
我刚刚找到了一种方法来做到这一点。
对于 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>
最好在整页模式下检查它。
要在其他浏览器中对此进行测试,您可以使用此 CodePen。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句