我正在尝试检测某个css类是否应用了背景图像。
我可以简单地执行以下操作来测试是否存在背景图像:
if ($('.vc_custom_1498122672544').css('background-image') != 'none') {
alert('There is a background image');
}
但是上述类是动态生成的,并不总是已知。
附加了此类的div也应用了一些其他类。所以我尝试了以下内容:
if ($('.vc_row-has-fill').css('background-image') != 'none') {
alert('There is a background image');
}
这不会返回任何内容,因为背景图片专门针对的是.vc_custom_1498122672544
而不是.vc_row-has-fill
。
我可以做些什么来检测课程.vc_row-has-fill
的背景图片吗?
答案 0 :(得分:1)
实际上,你可以检查一个类是否有另一个类。例如,类.vc_row-has-fill
的div具有类.vc_custom_1498122672544
或不具有类.vc_custom_1498122672544
。如果是,那么您可以进一步检查课程background-image
是否有$('.vc_row-has-fill').each(function(){
if ($(this).hasClass('vc_custom_1498122672544')){
if ($('.vc_custom_1498122672544').css('background-image') != 'none') {
alert('There is a background image');
}
}
});
absdiff
演示:https://jsfiddle.net/9y52ef4c/
我不确定,这是否是您想要实现的目标。希望能有所帮助
答案 1 :(得分:0)
实际上你可以使用这篇文章的方法: jquery -Get CSS properties values for a not yet applied class
那里的代码:
var getCSS = function (prop, fromClass) {
var $inspector = $("<div>").css('display', 'none').addClass(fromClass);
$("body").append($inspector); // add to DOM, in order to read the CSS property
try {
return $inspector.css(prop);
} finally {
$inspector.remove(); // and remove from DOM
}
};
基本上,您可以调用getCSS('backgroundImage', ***A class to test for a background image***)
并将其用作消除方法。
这对您的情况有帮助吗?
答案 2 :(得分:0)
理想情况下应该可以正常工作,但如果没有,那么您可以检查vc_custom_1498122672544
这样的课程是否始终以vc_custom_
开头并始终为具有课程vc_row-has-fill
的元素设置背景,然后您可以查看元素是否有任何以vc_custom
开头的类,如下所示。
if($(".vc_row-has-fill").is("[class*='vc_custom_']"))
{
alert('There is a background image');
}
或者使用@hallleron发布的链接中提到的功能,您可以查看如下。
$(document).ready(function() {
function hasBackgroundImageSet(fromClass) {
var $inspector = $("<div>").css('display', 'none').addClass(fromClass);
$("body").append($inspector);
try {
return $inspector.css('background-image') != 'none';
} finally {
$inspector.remove(); // and remove from DOM
}
};
var hasBg = $(".vc_row-has-fill").attr("class").split(" ").some(function(cls) {
return hasBackgroundImageSet(cls);
//return $("."+cls).css("background-image") != "none";//use this if not use above
});
if(hasBg){
alert('There is a background image');
}
});
答案 3 :(得分:0)
这是我提出的解决方案。我知道自定义类始终是应用于div的第3类。最后很简单:
$('.vc_row-has-fill').each(function(){
var classes = $(this).attr('class').split(' ');
var imgClass = classes[3];
if ($('.' + imgClass).css('background-image') != 'none') {
alert('There is a background image');
}
});