最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Check if an element has a background-image with pure JS? - Stack Overflow

programmeradmin0浏览0评论

What is the correct way to check if a particular element has a background-image associated with it, in pure Javascript?

Right now I have this:

var elementComputedStyle = window.getComputedStyle(element); 
var hasBGImage = elementComputedStyle.getPropertyValue('background-image') !== 'none'

What is the correct way to check if a particular element has a background-image associated with it, in pure Javascript?

Right now I have this:

var elementComputedStyle = window.getComputedStyle(element); 
var hasBGImage = elementComputedStyle.getPropertyValue('background-image') !== 'none'
Share Improve this question asked Aug 7, 2014 at 19:18 blackghostblackghost 7131 gold badge8 silver badges18 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

What you have works, but there are alternate ways of finding the property that you might find easier. I don't believe there is a single 'correct' way to do it, however.

Just javascript:

var hasBGImage = element.style.backgroundImage !== '';

Using jQuery:

var hasBGImage = $(element).css('background-image') !== 'none';

Make sure you declare the background image "inline", otherwise .style.backgroundImage won't work.

<script>
window.onload=function() {
    var bg = document.getElementById('el').style.backgroundImage.length!=0;
    alert(bg);
}
</script>
<div id='el' style="background-image: url('a.jpg');"></div>

If you can use inline CSS, that's the way. If, for some reason, you can't use that, let me know, I'll try to find out something else :)

I used this code in last one project and works perfect

    // Check all background images exists
var imageURLs = $('.image-container ');
imageURLs.each(function(index, element){
    var imageURL = $(element).css('background-image').replace('url("', '').replace('")', '');
    var img = new Image();
    img.onerror = function() { $(element).css('background-image','url(/build/images/missing-image.svg)'); };
    img.src = imageURL;
});
发布评论

评论列表(0)

  1. 暂无评论