Javascript - 覆盖先前在另一个函数中声明的样式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18295766/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript - Overriding styles previously declared in another function
提问by Yavierre
Ok, this is my HTML
好的,这是我的 HTML
<div id="plus" style="margin-left: 10px; margin-top: 303px;">
<div id="plus-back"> </div>
<div id="plus-ex"> X </div>
</div>
NOTE: the #plus
element's inline styles was declared previuously by another script
注意:#plus
元素的内联样式先前由另一个脚本声明
And this is my JS
这是我的 JS
document.getElementById("plus").onclick = showNav
document.getElementById("plus-ex").onclick = hideNav
function showNav(){
this.style.width="200px"
this.style.height="200px"
document.getElementById("plus-ex").style.display="block"
}
function hideNav(){
document.getElementById("plus").style.width="48px"
document.getElementById("plus").style.height="48px"
}
Well.. this is what i have. The goal is simple, when you click #plus
, this is expanded to show some content, and appears a "X" that is inside #plus-ex
, and when you click that "X", #plus
go back to the start (that is a div with 48px of height and width thanks to stylesheet). The problem with this, is that hideNav()
is not doing a good work. When you click #plus
, showNav()
function is fired successfully, but after that, when you click the "X" and hideNav() is fired (successfully too), that should apply the initial style, but does anything. I have tested applying another CSS propieties like background-color
and works OK, but not with width
and height
.
嗯..这就是我所拥有的。目标很简单,当你点击时#plus
,它会展开显示一些内容,并在里面出现一个“X”,#plus-ex
当你点击那个“X”时,#plus
回到开始(即一个高度为48px的div和宽度感谢样式表)。hideNav()
这样做的问题是没有做好。当您单击时#plus
,showNav()
函数被成功触发,但之后,当您单击“X”并触发 hideNav() 时(也成功),这应该应用初始样式,但可以执行任何操作。我已经测试过应用另一个 CSS 属性,例如background-color
并且可以正常工作,但不能使用width
和height
。
I think that the problem is that i can't override the styles applied by showNav()
我认为问题在于我无法覆盖应用的样式 showNav()
What should i do?
我该怎么办?
回答by vee
The problem is when you click X
the event is bubbling up to the #plus
div. You can prevent this by calling:
问题是当您单击X
事件时,该事件冒泡到#plus
div。您可以通过调用来防止这种情况:
event.stopPropagation();
Update your code as follows and give it a try:
按如下方式更新您的代码并尝试一下:
document.getElementById("plus").onclick = showNav
document.getElementById("plus-ex").onclick = hideNav
function showNav(){
this.style.width="200px"
this.style.height="200px"
document.getElementById("plus-ex").style.display="block" // Don't need this line as it's a block element i.e. already a div
event.stopPropagation(); // add this line
}
function hideNav(){
document.getElementById("plus").style.width="48px"
document.getElementById("plus").style.height="48px"
event.stopPropagation(); // add this line
}