jjzjj

javascript getBoundingClientRect() 值对于动态添加的元素是错误的

coder 2024-07-25 原文

无法在广泛的网络上找到答案,因此请在此处发布问题。

我想要实现的目标:

当用户滚动到页面底部时,获取最新动态加载元素的 bottom 值,并使用它来确定是否该加载另一个元素。

数学很简单:

if (element.getBoundingClientRect().bottom <= window.innerHeight)
   loadAnotherElement();

window.innerHeight is 955px

问题:

在初始加载时,第一个元素的 bottom 值为 905px 这很好并触发函数加载另一个元素,但在加载第二个元素后 bottom 值为 1389px 永远不会触发 loadAnotherElement 函数。

我无法发布完整的代码,因为它太复杂了,所以希望上面的内容足以理解。

编辑

设法创建一个合适的 test case

最佳答案

在您发布的 JS fiddle 中,它无法识别正确高度的原因是因为您的内部元素是 float 的。 float 不会影响父元素的高度,因此我建议采用以下解决方案:

article:after {
    width: 100%;
    clear: both;
    content: '';
    display: block;
}

我还稍微清理了 fiddle 并删除了不必要的部分,以便更容易看出错误在哪里(在您的部分之前和之后显示的表格样式没有任何优势)。

var last = document.querySelector('article');
document.addEventListener('scroll', function(){
    if(last.getBoundingClientRect().bottom <= window.innerHeight){
        var newElement = last.cloneNode(true);
        last.parentNode.appendChild(newElement);
        last = newElement;
    }
});
html,
body {
    height: 100%;
}

/* I have removed a bit of CSS that I think didn't really do anything at all. */

article {
    width: 100%;
    display: inline-block;
    border-bottom: 1px solid red;
}

/* This will create an element that will clear past the floats, stretching your article to the correct encapsulating size */

article:after {
    width: 100%;
    clear: both;
    content: '';
    display: block;
}

/* Some correction so they all stay neatly in line */

div {
    float: left;
    width: 30%;
    margin: 1.5%;
    height: 100vh;
    position: relative;
    background: blue;
}

div:nth-child(3n-2){ background: #666; }
div:nth-child(3n-1){ background: #888;  }
div:nth-child(3n){ background: #222; }
<section>
  <article>
    <!-- I made these 6 divs so they neatly pack six in an article. -->
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
  </article>
</section>

更新

如果您希望元素整齐地排成一行,为什么还要将它们包装在单独的元素中呢?简单地将元素创建为新的 sibling ,这将插入其最终大小:

var section = document.querySelector('section');
var article = document.querySelector('article');
document.addEventListener('scroll', function(){
    if(section.getBoundingClientRect().bottom <= window.innerHeight){
        section.appendChild(article.cloneNode(true));
    }
});
html,
body {
    height: 100%;
}

/* I have removed a bit of CSS that I think didn't really do anything at all. */

section {
    width: 100%;
    display: inline-block;
    border-bottom: 1px solid red;
}

/* This will create an element that will clear past the floats, stretching your article to the correct encapsulating size */

section:after {
    width: 100%;
    clear: both;
    content: '';
    display: block;
}

/* Some correction so they all stay neatly in line */

div {
    float: left;
    width: 30%;
    margin: 1.5%;
    height: 100vh;
    position: relative;
    background: blue;
}

div:nth-child(3n-2){ background: #666; }
div:nth-child(3n-1){ background: #888;  }
div:nth-child(3n){ background: #222; }
<section>
  <article>
    <!-- I made these 7 divs for illustrations sake. -->
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
  </article>
</section>

关于javascript getBoundingClientRect() 值对于动态添加的元素是错误的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36651547/

有关javascript getBoundingClientRect() 值对于动态添加的元素是错误的的更多相关文章

  1. ruby - 我需要将 Bundler 本身添加到 Gemfile 中吗? - 2

    当我使用Bundler时,是否需要在我的Gemfile中将其列为依赖项?毕竟,我的代码中有些地方需要它。例如,当我进行Bundler设置时:require"bundler/setup" 最佳答案 没有。您可以尝试,但首先您必须用鞋带将自己抬离地面。 关于ruby-我需要将Bundler本身添加到Gemfile中吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/4758609/

  2. ruby-on-rails - Rails 常用字符串(用于通知和错误信息等) - 2

    大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje

  3. ruby - 将 Bootstrap Less 添加到 Sinatra - 2

    我有一个ModularSinatra应用程序,我正在尝试将Bootstrap添加到应用程序中。get'/bootstrap/application.css'doless:"bootstrap/bootstrap"end我在views/bootstrap中有所有less文件,包括bootstrap.less。我收到这个错误:Less::ParseErrorat/bootstrap/application.css'reset.less'wasn'tfound.Bootstrap.less的第一行是://CSSReset@import"reset.less";我尝试了所有不同的路径格式,但它

  4. ruby - 续集在添加关联时访问many_to_many连接表 - 2

    我正在使用Sequel构建一个愿望list系统。我有一个wishlists和itemstable和一个items_wishlists连接表(该名称是续集选择的名称)。items_wishlists表还有一个用于facebookid的额外列(因此我可以存储opengraph操作),这是一个NOTNULL列。我还有Wishlist和Item具有续集many_to_many关联的模型已建立。Wishlist类也有:selectmany_to_many关联的选项设置为select:[:items.*,:items_wishlists__facebook_action_id].有没有一种方法可以

  5. ruby-on-rails - 迷你测试错误 : "NameError: uninitialized constant" - 2

    我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test

  6. ruby-on-rails - 如何在 Rails View 上显示错误消息? - 2

    我是rails的新手,想在form字段上应用验证。myviewsnew.html.erb.....模拟.rbclassSimulation{:in=>1..25,:message=>'Therowmustbebetween1and25'}end模拟Controller.rbclassSimulationsController我想检查模型类中row字段的整数范围,如果不在范围内则返回错误信息。我可以检查上面代码的范围,但无法返回错误消息提前致谢 最佳答案 关键是您使用的是模型表单,一种显示ActiveRecord模型实例属性的表单。c

  7. 使用 ACL 调用 upload_file 时出现 Ruby S3 "Access Denied"错误 - 2

    我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file

  8. ruby-on-rails - 错误 : Error installing pg: ERROR: Failed to build gem native extension - 2

    我克隆了一个rails仓库,我现在正尝试捆绑安装背景:OSXElCapitanruby2.2.3p173(2015-08-18修订版51636)[x86_64-darwin15]rails-v在您的Gemfile中列出的或native可用的任何gem源中找不到gem'pg(>=0)ruby​​'。运行bundleinstall以安装缺少的gem。bundleinstallFetchinggemmetadatafromhttps://rubygems.org/............Fetchingversionmetadatafromhttps://rubygems.org/...Fe

  9. ruby - #之间? Cooper 的 *Beginning Ruby* 中的错误或异常 - 2

    在Cooper的书BeginningRuby中,第166页有一个我无法重现的示例。classSongincludeComparableattr_accessor:lengthdef(other)@lengthother.lengthenddefinitialize(song_name,length)@song_name=song_name@length=lengthendenda=Song.new('Rockaroundtheclock',143)b=Song.new('BohemianRhapsody',544)c=Song.new('MinuteWaltz',60)a.betwee

  10. ruby-on-rails - 每次我尝试部署时,我都会得到 - (gcloud.preview.app.deploy) 错误响应 : [4] DEADLINE_EXCEEDED - 2

    我是Google云的新手,我正在尝试对其进行首次部署。我的第一个部署是RubyonRails项目。我基本上是在关注thisguideinthegoogleclouddocumentation.唯一的区别是我使用的是我自己的项目,而不是他们提供的“helloworld”项目。这是我的app.yaml文件runtime:customvm:trueentrypoint:bundleexecrackup-p8080-Eproductionconfig.ruresources:cpu:0.5memory_gb:1.3disk_size_gb:10当我转到我的项目目录并运行gcloudprevie

随机推荐