$(' .middle.clear > .post_home:first ').css('padding-left', '270px !important');这段代码在Firefox中从元素1开始,而在Chrome中从元素0开始。我该怎么对待它呢?
发布于 2012-02-22 12:39:26
你可以在很短的时间内达到类似的效果:
document.querySelector(".middle.clear > .post_home").style.paddingLeft = "270px";这里不需要!important,因为据我所知,内联样式总是优先的。
这样做的速度要快得多,因为jQuery必须在内部运行数百个命令来创建jQuery对象,然后再运行100个命令来设置对象上的CSS。
但是请注意,IE7及更低版本不支持querySelector,但this article提供了在IE7及更低版本中实现querySelector的绝佳方法。
发布于 2012-02-22 12:27:46
尝试使用eq()选择器指定要遍历的元素集中的索引。您还应该尝试避免嵌套许多类选择器,因为这可能导致较差的性能。请尝试使用ID。
此外,当您指定!important标记时,请确保在CSS样式和important标记之间不留空格。下面的代码将向元素中的第一个post_home类元素添加一个左填充CSS属性,该元素的类同时为clear和middle。
$('.middle.clear .post_home').eq(0).css('padding-left', '270px!important');发布于 2012-02-22 13:52:05
当所有的子元素都匹配时,像:first,:last,:nth-child(2)这样的选择器才能工作。
在您的示例中,$(' .middle.clear > .post_home:first ')将假定您具有以下结构
<div class="middle clear">
 <div class="post_home">
 <!-- content -->
 </div>
 <!-- no other element of class other than post_home allowed here -->
 <div class="post_home">
 <!-- content -->
 </div>
 <!-- no other element of class other than post_home allowed here -->
 <div class="post_home">
 <!-- content -->
 </div>
 <!-- no other element of class other than post_home allowed here -->
</div>这里所有的子元素都有post_home类,并且它们都由选择器匹配。你有一些其他的元素没有被它匹配,所以你得到了这个异常的行为。尝试使用$(' .middle.clear > .post_home ')[0].style.paddingLeft = "270px";或$(' .middle.clear > .post_home ').get(0).style.paddingLeft = "270px";
提示:如果你想使用这样的选择器,可以使用ul li结构。
https://stackoverflow.com/questions/9388227
复制相似问题