CSS优化:元素ID与类 [英] CSS Optimization: Element ID vs. Class

查看:114
本文介绍了CSS优化:元素ID与类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过MVC和jQuery,我更多地使用CSS。一个想到的问题是什么是使用元素ID与类的最佳方法。如果我使用元素ID,jQuery中的选择器更短。例如:

With MVC and jQuery I am making significantly more use of CSS. A question that came to mind is what is the best approach for using Element IDs vs. Classes. If I use Element IDs the selectors in jQuery are shorter. For example:

#imageTag... $('#imageTag')
#searchTag... $('#searchTag')

另一种方法是使用父容器元素。

As an alternative it could be structured with a parent container element.

#searchTool, #classifyTool .tag

在这种情况下,选择器如

In this case selectors such as

$('#searchTool .tag')或$('#classifyTool .tag')

$('#searchTool .tag') or $('#classifyTool .tag')

可以使用。当在整个页面中存在类的多个实例(例如,.tag)时,此方法可能特别有用。您只需更改父容器对象。

could be used. This approach can be particularly useful when there are multiple instances of a class throughout the page, e.g., .tag. You just change the parent container object.

这只是一个简单的理论示例,并不代表真实的风格,只是描绘的概念。

This is just a simple theoretical example and is not intended to represent real styles, just portray the concept.

这里有两个问题:


  1. / CSS或jQuery假设页面上有大量的样式?

  1. Is there any impact on performance of either the page/CSS or jQuery assuming there are a large # of styles on a page?

第二种方法看起来更加灵活和可维护。

The second approach seems more flexible and maintainable. Thoughts based upon your experiences.

有更好的替代方法吗?

感谢

推荐答案


  • ID是最快的

  • 标签名称最快。

  • 没有标签名称的类名是最慢的

  • 至于使用哪一个,使用最合适的。如果您的网页上有一个搜索框,则使用该ID最适合,因为只有一个搜索框。

    As for which one to use, use whichever is most appropriate. If you have a search box on your page then using an ID for that would be most appropriate because there's only one search box. Table rows on the other hand will probably be identified by class because there is (or can be) more than one.

    不要使用选择器(在CSS或jQuery中)像.class。你迫使jQuery或浏览器基本上遍历整个文档树。大多数时候,类将只应用于一种标记,因此指定(例如div.class)。这只会造成巨大的性能差异(特别是对于大型文档的jQuery)。

    Try not to use selectors (in CSS or jQuery) like ".class". You're forcing jQuery or the browser to basically traverse the entire document tree. Most of the time the class will only apply to one kind of tag so specify that (eg "div.class"). That alone can make a huge performance difference (particularly on jQuery with a large document).

    选择器的长度不应该是。性能,可读性和可维护性应该是。

    The length of the selector should not be a consideration. Performance, readability and maintainability should be.

    这篇关于CSS优化:元素ID与类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆