我想使用jquery来检测是否已在元素的style属性中设置了图像背景,然后如果存在,则确定图像的纵横比并将相关类添加到元素。
http://jsfiddle.net/2urn/9ydHG/37/
<article class="listing-article" style="background-image:
url('http://placehold.it/600x350/ff6600/fff');">
<div class="overlay"></div>
<div class="article-summary">
<h2 class="post-title post">Horizontal Background</h2>
<section class="article-excerpt">
<h3 class="subhead">Subhead</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.</p>
</section>
</div>
</article>
我在小提琴的js窗口中引用了一些相关的堆栈文章,但是对于我的水平而言,代码太复杂了。
任何帮助,不胜感激。
这是jQuery要做的事情。评论了这些部分以便于阅读:
$(document).ready(function() {
// Loop through all the articles.
$('.listing-article').each(function() {
var $article = $(this);
// Check if they have a background image.
if ($article.css('background-image') !== 'none') {
$article.addClass('bg-img');
// Extract background url.
var articleBG = $article.css('background-image').replace('url(','').replace(')','');
// Load up the image to get its dimension.
$('<img src="'+ articleBG +'"/>').load(function(){
var imgWidth = this.width;
var imgHeight = this.height;
if (imgWidth === imgHeight) {
$article.addClass('bg-square');
}
else if (imgWidth > imgHeight) {
$article.addClass('bg-horizontal');
}
else {
$article.addClass('bg-vertical');
}
});
}
else {
$article.addClass('bg-none');
}
});
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句