ID vs Class 陈词滥调的选择器题目

昨天看了下那本《CSS3秘笈》, 在关于CSS选择器一章中提到应当只管防止运用ID选择器, 这我就疑惑了, 之前好像没太注重, 书中的理由是ID选择器权重太高, 缺少灵活性, 而且引用了一篇文章来论述缘由(原文地点:When using IDs can be a pain in the class…) 这里直接用原文中作者的DEMO原文DEMO地点 来议论下,作者的意义是在页脚运用.twitter a 定义好链接色彩后,将该链接加入到页眉上时会由于页眉运用了ID选择器而遭到滋扰

Let’s imagine you’re building a site and one of the requirements is to have a reusable Twitter widget that needs to be placable wherever the client chooses. Let’s for example say they want to kick things off with having the widget in the header and also in-page, at the bottom of an article. The Twitter widget’s styling must remain consistent.

以下是demo的截图:
《ID vs Class 陈词滥调的选择器题目》

这篇文章有肯定原理, 在CSS规划时确切存在这个题目, 也不便于扩大,然则ID选择器在JS中确是最快的, 由于JS查找ID元素时一经找到就住手查找,而查找类元素则组要遍历全部DOM, 这个题目在stackoverflow的议论(id vs class selection benchmark) 基于css规划与js机能的斟酌, 我以为是不是能够在触及js操纵的DOM节点只管地运用ID 选择器, 而在CSS规划上只管防止, 比方一个HTML元素上既写ID又写Class ,ID用于JS操纵, class用于css款式规划,像如许:

<div id="btn" class="btn"></div>

别的直接放个选择器的测试网站,内里有包含jq,yui等框架选择器的测试Speed/validity selectors test for frameworks.

    原文作者:囧囧
    原文地址: https://segmentfault.com/a/1190000003945444
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞