简体   繁体   English

为什么style.display的值未定义?

[英]Why is style.display's value undefined?

What could be a reason for an element's style.display returning the value undefined ? 元素的style.display返回值undefined的原因可能是什么?

In my Javascript, I have an if statement checking 在我的Javascript中,我有一个if语句检查

if (document.getElementById("myModal").style.display != 'none'){ 
    console.log("The pop up is visible.");
    do something
}

In my CSS, I have myModal set to display: none; 在我的CSS中,将myModal设置为display: none;

myModal is a pop up form that is accessed through click. myModal是可通过单击访问的弹出表单。

I moved my <script> for the js file to the bottom of the HTML, doesn't this ensure that my DOM is fully loaded before the javascript is run? 我将js文件的<script>移到了HTML的底部,这是否可以确保在运行javascript之前已完全加载DOM? However, the console.log displays as soon as the page is loaded even though the conditional is not met (ie the pop up is currently not visible). 但是,即使不满足条件(即使弹出窗口当前不可见),也会在页面加载后立即显示console.log

Not sure if the Leaflet API has anything to do with this? 不确定Leaflet API是否与此有关?

What you have in your CSS stylesheets has little to do with the style property of your element. CSS样式表中的内容与元素的style属性无关。 The style property only includes inline styles. 样式属性仅包括嵌入式样式。 Notice how in this code the first div has an empty style.display , even though it is display: none because of the stylesheet; 请注意,在此代码中,第一个div如何display: none为空style.display ,即使它是display: none因为样式表,所以display: none only the second and third div have style.display properties set to anything: 只有第二个和第三个div的style.display属性设置为任意值:

 const divs = document.querySelectorAll( 'div' ); [].forEach.call( divs, div => document.body.innerHTML += div.style.display + '<br>' ); 
 div { display: none; } 
 <h2>Divs:</h2> <div>One</div> <div style="display:none;">Two</div> <div style="display:block;">Three</div> <h2>Styles:</h2> 

If you want to get the computed style of an element, considering all stylesheets and inline styles, you can use getComputedStyle . 如果要获取元素的计算样式,请考虑所有样式表和内联样式,可以使用getComputedStyle Or you can just use jQuery: 或者,您可以只使用jQuery:

if ( $('#myModal').is(':visible') ) {
    console.log("The pop up is visible.");
}

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

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