0

显示最初要隐藏的 HTML 元素的最佳做法是什么?

  • 在 HTML 中创建元素并使用 CSS 隐藏它。当需要使用它时,用 JavaScript 展示它。
  • 当需要该元素时,使用 JavaScript 创建并显示它。

前者的缺点是 HTML 中可能存在不必要的元素,并且最初必须使用 CSS 隐藏。后者的缺点是 HTML 位于 JavaScript 文件中。

编辑:添加示例

一个示例是添加加载指示器或显示模式窗口。

4

2 回答 2

2

There are a lot more factors that go in to this. If you are inserting a small element like a link or select list options, then dynamically generating them in javascript is a non-issue. If you are generating a repeating series of complex HTML, it might be a good idea to create a template of the html in the markup (so that the web designers can maintain it) and then make the template hidden in CSS. Then use javascript (e.g. jQuery) to clone the template and insert it in to the DOM. This gives you the benefit of using more native implementations to extend the DOM tree without all the nasty javascript-that-parses HTML mess.

But ultimately the practicality comes down to this: Who is going to maintain the code? Will the more elegant solution be something that the maintainer will understand? Or will putting everything in javascript (despite its inelegance) be something that a junior coder would be able to expand or update as the need arises in the future?

The vast majority of web browsers run on hardware that is ridiculously over-powered for what the user actually "needs", at least in terms of web browsing. Because of this, inefficient solutions in Javascript are rarely ever an immediate issue. If you are targeting mobile browsers though, efficiency == battery life. So if you are doing heavy dom-manipulation then consider the suggestion above and see if it works for your case.

Best of luck! -Brendan

于 2013-01-17T17:31:13.870 回答
1

The answer to that question used to be very heavily biased towards "Don't create it until you need to."

The reasons behind that decision are still somewhat applicable,but no-where near as much as they were.

  • People running a browser with styles off will see your hidden content. They'll also see a very ugly web. I wouldn't worry about it.
  • People running very ancient browsers that don't support styles will see it. They'll also see a very broken web. I'd not worry about them either
  • Screen readers will pick it up. Modern screen readers seem to be much better at realizing what content is, and is not visible. If you need ADA compliance, or just want to be responsible, some testing might be done there.
  • Sometimes, when printing, hidden content would be picked up. Again, not an issue.

All said, I'd do for hiding it through CSS rather than trying to dynamically add the content.

于 2013-01-17T17:30:57.417 回答