gpt4 book ai didi

javascript - 检查元素的 scrollHeight 有时会返回 0

转载 作者:行者123 更新时间:2023-11-28 18:55:15 26 4
gpt4 key购买 nike

所以我正在检查一些动态生成的内容的滚动高度,以确定是否在内容中包含更多按钮。用户可以点击更多按钮来展开内容并查看里面的所有内容。然而,每次使用相同的函数时,有时它会说元素的 scrollHeight 为 0,这不用说会破坏这些元素的功能。我非常不明白为什么这个函数在 90% 的时间里都能正常工作,但有时会说元素没有 scrollHeight 而实际上它们显然有(它们占用页面上的空间)。

函数如下:

function hide_show_expand_button(length){
var current_div = '';
var current_span = '';
//console.log(length);
for(var i = 0; i < length; i++){
if(document.getElementById("message_span"+i)){
current_div = document.getElementById("items_content"+i);
current_span = document.getElementById("message_span"+i);
console.log(current_div.scrollHeight, "height of the div")
if(current_span.scrollHeight > 128 && current_div.scrollHeight < 170){
console.log("inside of the check for the conversation screen");
current_div.innerHTML +="<a href=\"#\" id='expand_colapse_button"+i+"' class=\"expand_colapse_button_conversation\" style=\"color:blue;\" onclick='expand_colapse(\""+ i + "\")'>More...</a>";
} else if(current_span.scrollHeight > 128 && document.getElementById("items_content"+i).scrollHeight > 200 ){
current_div.innerHTML+="<a href=\"#\" id='expand_colapse_button"+i+"' class=\"expand_colapse_button_attatchment\" style=\"color:blue;\" onclick='expand_colapse(\""+ i + "\")'>More...</a>";
} else if(current_span.scrollHeight > 128 && current_div.scrollHeight < 200){
current_div.innerHTML +="<a href=\"#\" id='expand_colapse_button"+i+"' class=\"expand_colapse_button\" style=\"color:blue;\" onclick='expand_colapse(\""+ i + "\")'>More...</a>";
}
}
}
}

如您所见,我正在检查 span 和 div 上的 scrollHeight,因为我生成了几种不同类型的单元格,我必须根据单元格类型将更多按钮放置在不同的位置.这个函数只在生成被检查内容的函数结束时被调用,我已经用 setTimeout() 调用尝试过它,因为它在它们完全完成之前通过这个函数的机会很小创建(我不知道那会如何发生,但谁知道)。

附言这一切都发生在 chrome ext 中。我不认为这与它有任何关系,但谁知道呢。元素上的位置也是相对的,因为我看到其他人发布了关于 position: absolute 的 scrollHeight 问题。

编辑更具体:

希望这会有所帮助,我尝试测量的单元格位于一个包含 div 中,该 div 可以通过几种不同的方式将其显示设置为无。上面发生的事情发生在我从容器导航离开(将显示设置为无)然后导航回它(将显示设置为阻止)的情况之一。您可以在 chrome ext 中以十几种方式执行此操作。但它只说他们没有 scrollHeight(或我尝试使用 getBoundingClientRect() 的任何高度,并且它为所有内容返回 0)对于一种情况,这就是我感到困惑的原因。

了解此信息可能也很有用,在导航回容器时,每次都会重建单元格,正如我上面所述,我在构建单元格的函数末尾调用了获取 scrollHeight 的函数。所以每次你回到容器时,我的函数也会被调用。

最佳答案

我建议查看这些(我找不到适用于 Chrome 的类似链接):

MSDN:http://msdn.microsoft.com/en-us/library/ms530302%28v=VS.85%29.aspx

莫兹:https://developer.mozilla.org/en/Determining_the_dimensions_of_elements

似乎 scrollHeight 仅在某些内容大到需要滚动时才有效,因此我假设 0 表示不需要滚动(所有内容都可见)。从上面的链接来看,也许您想要的是 clientHeight。

关于javascript - 检查元素的 scrollHeight 有时会返回 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8100099/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com