繁体   English   中英

JavaScript-使用.offsetHeight的If语句不起作用

[英]JavaScript - If statement using .offsetHeight not working

我是JavaScript新手,正在练习。 我正在尝试显示h1和p元素的组合高度,这些高度在div中具有“ test”的类名称。 我查了各种各样的东西,觉得自己真的很亲密,但不能完全解决这个问题。 有人能帮忙吗?

HTML:

<div class="test">
    <h1>Understanding Scope</h1>
    <p>By understanding code's <em>scope</em>, we know when that code affects only one part of our code, or the entire codebase.  If we create things that are <em>global</em> in scope, we are giving any code the supreme power to control our code.   So we want to protect our code by being very careful when creating things that are global in scope. This is especially important if you plan on using JavaScript libraries like jQuery.</p>
</div>
<h1>Local Scope</h1>
<p>JavaScript uses <em>function scope</em>, meaning every time we create a new function the scope changes.  Any code inside that function is <em>local</em> to that function. Code that is local in scope is not accessible to outside code.</p>

JavaScript:

function testing(){
    if (document.getElementsByClass('test')){
        var headerHeight = document.getElementsByTagName('h1').offsetHeight;
        var textHeight = document.getElementsByTagName('p').offsetHeight;
        var totalHeight = headerHeight + textHeight;

        alert(totalHeight);
    }
}

testing();

它是document.getElementsByClassName,而不是getElementsByClass,而且您正在获取h1和p标签的数组

function testing(){
    if (document.getElementsByClassName('test')){
        var headerHeight = document.getElementsByTagName('h1')[0].offsetHeight;
        var textHeight = document.getElementsByTagName('p')[0].offsetHeight;
        var totalHeight = headerHeight + textHeight;

        alert(totalHeight);
    }
}

testing();
function testing(){
    if (document.getElementsByClassName('test')){

        var headerHeight = document.getElementsByTagName('h1')[0].offsetHeight;
        var textHeight = document.getElementsByTagName('p')[0].offsetHeight;
        var totalHeight = headerHeight + textHeight;

        alert(totalHeight);
    }
}

testing();

暂无
暂无

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

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