[英]Show div hidden by “display: none” using JS?
The below HTML and JavaScript is working as expected, but I want to make sure I am using this correctly. 下面的HTML和JavaScript可以按预期工作,但是我想确保自己使用正确。
I have two divs but only one needs to be displayed depending on the value of mode
. 我有两个div,但根据
mode
的值,只需要显示一个即可。
HTML: HTML:
<body>
<div id="a-div" style="display: none;">
<button id="add" class="btnstyle">Add </button>
</div>
<div id="d-div" style="display: none;">
<button id="delete" class="btnstyle">Delete</button>
</div>
</body>
JS: JS:
//$("#a-div").hide();
//$("#d-div").hide();
var mode = 'add';
//var mode = 'delete';
if (mode === 'add') {
$("#a-div").show();
} else {
$("#d-div").show();
}
This is giving me expected results. 这给了我预期的结果。 Is there a better way of reversing the
style="display: none"
attribute? 有没有更好的方法来反转
style="display: none"
属性?
Your current code should be working fine, but there are many ways of solving this problem. 您当前的代码应该可以正常工作,但是有很多方法可以解决此问题。 I would recommend using jQuerys
toggle()
: 我建议使用jQuerys
toggle()
:
$("#a-div").toggle(mode === "add");
$("#a-div").toggle(mode === "delete");
Alternatively, you could give them the id´s add-div
and delete-div
and make one of them visible like this: 另外,您可以给他们一个id的
add-div
和delete-div
,使其中一个可见,如下所示:
$("#" + mode + "-div").show();
You can use: 您可以使用:
$("#a-div").toggle();
Alternatively; 另外;
.show()
/ .hide()
.show()
/ .show()
.hide()
.fadeIn()
/ fadeOut()
.fadeIn()
/ fadeOut()
You need to modify the display property of the inline style attribute. 您需要修改内联样式属性的显示属性。
Like this... 像这样...
var mode = 'add';
if (mode === 'add') {
$("#a-div")[0].style.display = 'block';
} else {
$("#d-div")[0].style.display = 'block';
}
Or you can use something like inherit
instead of block
. 或者,您可以使用诸如
inherit
之类的东西来代替block
。
There's several methods to do this (like you can see in other answers) but i think the show()
function is enough and do the work in your case. 有几种方法可以做到这一点(就像您可以在其他答案中看到的那样),但是我认为
show()
函数足以满足您的情况。
You can also use css()
method of JQuery like following : 您还可以使用JQuery的
css()
方法,如下所示:
$("#a-div").css('display','block');
Hope this helps. 希望这可以帮助。
Another option is to move the styles to css: 另一个选择是将样式移动到CSS:
html: HTML:
<div id="a-div" class="notdisplayed">
<button id="add" class="btnstyle">Add </button>
</div>
<div id="d-div" class="notdisplayed">
<button id="delete" class="btnstyle">Delete</button>
</div>
css: CSS:
.notDisplayed {display:none;}
Script: 脚本:
$("#a-div").addClass("notDisplayed");
$("#d-div").removeClass("notDisplayed");
This method is more general than show/hide, as it can be extended to any style rule. 此方法比show / hide更通用,因为它可以扩展到任何样式规则。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.