I expect to toggle an element's visibility: should I start with class="..." or style="..."?
If I have an element on a web page that I expect to be showing and hiding quite a bit using javascript, which would be the most appropriate way to set it as initially invisible?
<div class="hidden">...</div>
or
<div style="disp开发者_JS百科lay: none;">...</div>
Using class="..."
is preferable to style="..."
in most cases, but I'm not convinced it's the best fit in this case. Semantically, my element isn't a hidden element, it's just one that will start off hidden when the page first loads. As I'm using jQuery's show() and hide() methods, it means it'll often be in this state:
<div class="hidden" style="display: block;">...</div>
.. which to me is plainly nonsense.
On the other hand, using an in-line style="display: none;"
feels somehow hacky and hard-coded.
I'm aware that either method will work perfectly and the user will never be any the wiser, but which pattern violates design principles the least?
Call the style initially-hidden
. It accurately conveys the information, and makes sense if you were to ever query for that style using jQuery.
I think if you're going to toggle by changing display around from "" to "none", you should use style. If you're going to toggle by changing class from "hidden" to "", you should use class. In other words, be consistent.
While I agree about having a whole class to just call out the initial visibility of something might seem a bit much it does make it easier to figure out what is going on. Especially if you name it something descriptive such as 'initially-hidden' as was suggested earlier.
So while I can't call out a specific design principal I think what I'm suggesting has its merits. This is more maintainable than either applying a direct style that you could not reuse and more obvious as to whats happening than a call to hide() using jQuery.
精彩评论