Best Practice (jQuery, CSS): How to initialize hidden elements that will toggle visible?

£可爱£侵袭症+ 提交于 2019-12-12 08:55:30

问题


Stack is warning me this is a subjective question, and will likely be close, but I'm going to try this anyway.

I have a set of control buttons attached to pictures in a gallery. These are to be initially hidden, and toggle visible when the mouse hovers over the image. The question I have is this:

Should these buttons be set to hidden in the stylesheet or stay visible and be hidden by jQuery when they load? I want graceful degradation, so it seems like initializing this in the CSS is a bad idea if I want these to be visible if javascript isn't enabled.

On top of this, I'm using Ajax to load pages of these images. If I do this using the jQuery hide, it doesn't affect those that load from an ajax request, since it only triggers on $(document).ready(). I've tried using live('ready'), but learned that that event isn't supported in live().

So what is the best practice for something like this? It seems like there's a lot of pros and cons for doing this either way (css vs. document.ready), and if they're hidden by the default CSS, the buttons will toggle fine with ajax pagination. But if javascript isn't enabled, the functionality of the buttons will be lost. Does anyone have advice for this?

Note: I didn't mention it originally, but it is significant. I'm currently using fadeToggle() to accomplish my transition, which may be what's complicating this whole issue. The solutions so far all appear to work, but not so much when fading is introduced.


回答1:


If you're trying to change the style of elements loaded via Ajax, it's almost like you're trying to hit a moving target. I would create two declarations in my stylesheet - one for hidden, one for visible - and then toggle them based on a class attached to the body tag (or any other containing tag).

Like so:

body .mybutton {
  display:block;
}

body.loaded .mybutton {
  display:none;
}

Then in your JS file:

$(document).ready(function() {
  $('body').addClass('loaded');
});

This way, any elements that have the class name mybutton - current and future - will have the appropriate style applied.




回答2:


You hide with CSS initially using display:none; then use jQuery's toggle() to show and hide again. This is the best way to do it. As for people that do not have JavaScript enabled, i wouldn't worry about that. They make 1% of users. Everyone have JavaScript enabled.

Check working example http://jsfiddle.net/znJxh/



来源:https://stackoverflow.com/questions/5603645/best-practice-jquery-css-how-to-initialize-hidden-elements-that-will-toggle

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!