简体   繁体   English

使用 Javascript 更改 CSS Display 属性但一直消失

[英]Changing CSS Display property with Javascript but keeps disappearing

I have a div element in my page which I want to make visible only upon the click of a button.我的页面中有一个 div 元素,我只想在单击按钮时使其可见。 This works as expected, except the div promptly disappears again and I cannot get it to remain visible.这按预期工作,除了 div 立即再次消失并且我无法让它保持可见。

 function btnAddItem_Click() { document.getElementById("add-item-popup").style.display = "block" }
 .add-item-popup { width: 400px; height: 550px; display: none; background-color: #ededed; position: fixed; right: 40%; top: 20%; }
 <div class="add-item-popup" id="add-item-popup"> //Contains a form </div> <button onclick="btnAddItem_Click()">Add Item</button>

I'm going to make a reasonable assumption but an assumption nonetheless with this solution.我将做出一个合理的假设,但仍然使用此解决方案进行假设。 The assumption is your <button> tag with your onclick handler is inside of another form.假设是您的<button>标记与您的onclick处理程序另一个表单内。 If so, replace this line here:如果是这样,请在此处替换此行:

<button onclick="btnAddItem_Click()">Add Item</button>

To become this code:要成为这个代码:

<button type="button" onclick="btnAddItem_Click()">Add Item</button>

Explanation: When button is inside a form without type="button" specified, it will submit the form, and in your case, reload the page where the css then of course is anew.说明:当按钮位于未指定type="button"的表单内时,它将提交表单,在您的情况下,重新加载 css 页面,然后当然是新的。 Thus you only see a "blip" of the displayed div.因此,您只能看到所显示 div 的“blip”。

Use This Code your issue is resolved.使用此代码您的问题已解决。

 function myFunction() { var x = document.getElementById("myDIV"); if (x.style.display === "none") { x.style.display = "block"; } else { x.style.display = "none"; } }
 #myDIV { width: 100%; padding: 50px 0; text-align: center; background-color: lightblue; margin-top: 20px; }
 <button onclick="myFunction()">Try it</button> <div id="myDIV"> This is my DIV element. </div>

I also agree with @GetSet, I created this little jsfiddle in order to reproduce the issue inside a form.我也同意@GetSet,我创建了这个小 jsfiddle 来重现表单中的问题。 In case we don't form, there's no issue.如果我们不形成,就没有问题。

You can reproduce the issue by removing/adding the button attribute type like recomended by @GetSet.您可以通过删除/添加@GetSet 推荐的按钮属性类型来重现该问题。

[Here it is an example][1]

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

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