0

我是 JavaScript 新手,正在练习。我正在尝试显示类名为“test”的 div 中 h1 和 p 元素的组合高度。我查了各种各样的东西,觉得我真的很接近,但不能完全让它发挥作用。有谁能帮忙吗?

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();
4

2 回答 2

0

它是 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();
于 2015-05-28T17:03:59.287 回答
0
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);
    }
}

测试();

于 2015-05-28T17:04:35.090 回答