开发者

Should classes that are used for selection in JavaScript be defined in the CSS file?

Our designer is calling for us to add the classes we use for JavaScript selectors to the CSS file with a comment stating that they're for JavaScript use. The intention is to avoid conflicts of interest; the case being made that a designer might remove a class from an element because no styling is applied.

For example, markup might be:

<div id="Book1" class="book">
</div>

and then if the "book" class is used for JavaScript selection, the CSS file would include this:

.book {/* Used as a JavaScript selector */}

Are there examples of where thi开发者_高级运维s technique is used, and why should it (or should it not) be used? I'm looking for examples of drawbacks, advantages and standards or official recommendations for this technique.


This is simply your designer looking for some form of control over the css to ensure that his / her changes do not break the client side functionality in your site. The problem with this however is that you are now mixing functionality with styling which in a well designed site should be seperate in the first place.

It's better to ensure that you create classes on the elements that you wish to target which have no styling associated and are used only for client side js purposes. You could always agree a convention whereby you prefix all such classes with 'js' such as jsMYCLASS and then reference them using something like the following jquery syntax;

<div class='book jsBookItem'></div>

target with:

$('.jsBookItem');

In this example you can see that the original 'book' style sits nicely beside the non styled class yet your designer can alter / remove the 'book' style independently of your client side code which now only relies on 'jsBookItem'.

The other main problem with his / her suggestion is that it will bloat the css files and increase the time taken to download / cache the stylesheets with no benefit to the end client. Even minifying the css would still leave blocks that are partially valid but not used.


I believe this technique is extremely important when more than one developer use to work on a project. Question is: How should someone know if a class is still relevant or already outdated?

You can also apply different rules to make JS selectors identifiable. I like to use a prefix like jss_ ore something like that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜