简体   繁体   English

隐藏HTML内容的正确方法

[英]correct way of hiding HTML content

I am writing a small HTML+JavaScript (so to call) application. 我正在编写一个小的HTML + JavaScript(可以调用)应用程序。 User is given two choices (radio buttons) and depending what did he choose, I display content "A" or content "B" under the choice radio buttons. 用户有两个选择(单选按钮),根据选择的内容,我在选择单选按钮下显示内容“ A”或内容“ B”。

Now I am wondering what is a right way to handle this content. 现在,我想知道什么是处理此内容的正确方法。 Should I have 2 DIVs, only one visible, depending on choice, or should I use JavaScript to write InnerHTML to single div, depending on a state of radio buttons. 根据选择,应该有2个DIV,只有一个可见,还是应该使用JavaScript将InnerHTML写入单个div,具体取决于单选按钮的状态。 This is small "calculation" application, so no forms data will be submitted. 这是一个小的“计算”应用程序,因此不会提交任何表单数据。

Thanks for replies! 感谢您的答复! J Ĵ

You can use: 您可以使用:

.myDivHidden
{
   display: none;
}

.myDiv
{
   display: block;
}

<div id="myDiv">
   Content
</div>

or 要么

.myDivInvisible
{
   visibility: hidden;
}
.myDivVisible
{
   visibility: visible;
}

<div id="myDiv">
   Content
</div>

The difference is that display: none; 区别在于display: none; will cause the element to disappear from the visible screen as if it is not even there, whereas visibility: hidden; 会导致元素从可见屏幕中消失,就像它不在那儿一样visibility: hidden; will cause the element to disappear from view but still take up the space and other elements will not shift into the empty space like they would is you use display: none; 会导致该元素从视图中消失,但仍会占用空间,其他元素不会像您使用display: none;那样移入空白空间display: none; .

Then you can swap the styles using JavaScript: 然后,您可以使用JavaScript交换样式:

if (radio button check goes here)
{
   document.getElementById('myDiv').className = className; // display or visibility
}
else
{
   document.getElementById('myDiv').className = className; // display or visibility
}

Just swap the visibility classes according to the method you would prefer to use 只需根据您希望使用的方法交换可见性类

Use two divs, both belonging to a CSS class that includes the display: none rule. 使用两个div,它们都属于包含display: none规则的CSS类。 Then when the user selects a choice, override that CSS on the div you want displayed and undo the override on what you do not want to show. 然后,当用户选择一个选项时,在要显示的div上覆盖该CSS,并在不希望显示的内容上撤消覆盖。 For example, if the user selects choice 1: 例如,如果用户选择选项1:

div1.style.display = 'block';
div2.style.display = '';

It's better to have 2 div and display the one which needs to be displayed. 最好有2格并显示需要显示的格。 Dynamically writing the content makes it too hard to design it and brings no real value. 动态地编写内容使其很难设计,并且没有真正的价值。

Use the 2 divs. 使用2格。 Embeding HTML into Javascript is ugly and makes it difficult to layout you page. 将HTML嵌入Javascript很难看,而且很难布局页面。

Use both divs and then use display: none; 同时使用两个div,然后使用display: none; for the div to hide. 让div隐藏。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM