Javascript获取元素高度不起作用

我需要根据元素高度切换按钮。尝试了 offsetHeight、clientHeight 和 scrollHeight,这些都不起作用。设置 alert() 用于测试目的,离开返回未定义。


    window.onload = function (){

    var wrapperHeight = document.getElementsByClassName("panel").offsetHeight;

    var innerHeight = document.getElementsByClassName("description-content").offsetHeight;

    var button = document.getElementsByClassName("accordion");

    if(innerHeight > wrapperHeight){

        button.style.display = "block";

    }

    alert(innerHeight);

}


胡说叔叔
浏览 423回答 2
2回答

ABOUTYOU

您应该放在[0]selector 之后document.getElementsByClassName("panel"),因为document.getElementsByClassName("panel")返回一个带有类“panel”的元素列表(数组),那么我建议使用 ID 并document.getElementById("panel_id");改为 put 以避免这些问题。这是您的代码:(带类)window.onload = function (){    var wrapperHeight = document.getElementsByClassName("panel")[0].outerHeight;    var innerHeight = document.getElementsByClassName("description-content")[0].outerHeight;    var button = document.getElementsByClassName("accordion")[0];    if(innerHeight > wrapperHeight){        button.style.display = "block";    }    alert(innerHeight);}这是您的代码(带有 ID):window.onload = function (){        var wrapperHeight = document.getElementById("panel_id").outerHeight;        var innerHeight = document.getElementById("description-content_id").outerHeight;        var button = document.getElementById("accordion_id");        if(innerHeight > wrapperHeight){            button.style.display = "block";        }        alert(innerHeight);    }

SMILET

您需要使用 style.height 属性。试试这个:window.onload = function (){    var wrapperHeight = document.getElementsByClassName("panel")[0].style.height;    var innerHeight = document.getElementsByClassName("description-content")[0].style.height;    var button = document.getElementsByClassName("accordion");    if(innerHeight > wrapperHeight){        button.style.display = "block";    }    alert(innerHeight);}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript