下面的javascript在我的post内容中将类附加到img标记的第一个实例。但根本不起作用。
<script type="text/javascript">
$(document).ready(function(){
var entries = document.querySelectorAll('.post-content');
for (var i = 0; i < entries.length; i++) {
var firstImage = $(entries[i].querySelectorAll('img:first')[0]);
firstImage.addClass('post-first-img');
}
});
</script>我的类已经做好了准备,可以在上面的工作中使用。
.main-content .post-content .post-first-img { min-width: 890px; }我也试过了,但没起作用。
.main-content .post-content img.post-first-img { min-width: 890px; }Live:http://highways.designlocker.co.uk/hitex-has-innovative-solutions-for-road-marking-and-surfacing/
发布于 2015-01-07 00:02:03
这是因为在普通的CSS中没有:first选择器。它只存在于jQuery中,但与依赖于原生CSS选择器的querySelectorAll一起使用。
只要把它移开就行了。
但是既然您已经使用了jQuery,为什么不使用
$('.post-content').each(function(){
$(this).find('img:first').addClass('post-first-img');
});发布于 2015-01-07 00:06:33
看起来,所有元素都包装在<p>标记中,所以这使得所有仅为p标记的图像都有0的索引。您需要做的是针对第一个<p>元素并将类应用于其第一个映像元素。
与…有关的东西:
$('.post-content p:first-child img:first-of-type').addClass('post-first-img');发布于 2015-01-07 00:09:23
您正在将本地DOM方法与jQuery方法混合使用,这可能会导致一些混淆。选择器:first是jQuery的一部分,您是通过DOM函数使用它的。
由于您已经在使用jQuery,我建议您将所有querySelectorAll调用转换为jQuery调用:
$(document).ready(function() {
var entries = $('.post-content');
entries.each(function() {
var firstImage = $(this).find('img:first');
firstImage.addClass('post-first-img');
});
});注意:上面的代码可以变得更短,我只是把它保持在与原始代码类似的格式,这样您就可以更好地理解它。
https://stackoverflow.com/questions/27809348
复制相似问题