使用纯 JavaScript 获取元素的尺寸和位置[重复]

2023-12-23

情况:我想获取元素的尺寸和位置

Context:我正在制作一款纸牌游戏。卡片可以放置在板上。我需要能够检查他们的目的地是否在板上。然后我将存储它们相对于板的尺寸和位置的位置。这将有助于在可能使用不同屏幕尺寸的一群不同客户之间重现该板。

目前的造型:

板的尺寸宽度和高度定义为:

width: 100%;
flex-grow:1;

它的容器具有以下属性:

display: flex;
flex-direction: column;

董事会形象 https://i.stack.imgur.com/BvaBK.png

您应该注意,实际尺寸是[942.922x874]。我找不到位置信息,我假设是因为默认 div 位置:静态而不是位置:绝对。

我的尝试:

let board = document.getElementById("gameboard");
if (board) {
  console.log("style.height", board.style.height);
  console.log("style.width", board.style.width);
  console.log("offsetHeight", board.offsetHeight);
  console.log("offsetWidth", board.offsetWidth);
  console.log("getBoundingClientRect" , board.getBoundingClientRect());
}

我的尝试的输出 https://i.stack.imgur.com/cKeUr.png

请注意,输出尺寸与我的实际尺寸不同。 [1137, 920] 而不是 [942.922x874]。 [1137, 920]实际上是整个身体的尺寸。而且,无论我做什么来获得位置,它总是给我[0,0]。

EDIT-1

我们得出的结论是,这可能是一个时间问题。我需要确保检索尺寸和位置的代码在元素渲染后运行。因为我正在使用反应,所以我发现了这个线程,ReactJS - 获取元素的高度 https://stackoverflow.com/questions/35153599/reactjs-get-height-of-an-element。这基本上是说我需要挂钩 React 的组件生命周期方法 componentDidMount() ,该方法在渲染完成后立即运行。您可以在下面看到我的实现。然而,即使使用此实现,我似乎仍然获得主体容器的尺寸而不是我正在访问的元素。

import React, {PureComponent, PropTypes} from 'react';
// import Card from '../../Components/Card/index.js';
// import Collection from '../../Components/Collection/index.js';
import {List} from 'immutable';
import Indicator from '../../Components/Indicator/index.js';
import Counter from '../../Components/Counter/index.js';
import {connect} from 'react-redux';
import * as actionCreators from './../../action_creators.js';
import './styles.scss';

export default class Game extends PureComponent {
  componentDidMount() {
    let board = document.getElementById("gameboard");
    console.log("getBoundingClientRect" , board.getBoundingClientRect());
  }
  render() {
    let playersById = this.props.playersById;
    let collections = this.props.collections;
    let counters = this.props.counters;

    let indic_list = [];
    let coll_list = [];

    //Indicators
    playersById.forEach(function(value, key, map){
      indic_list.push(<p className="section-name">{playersById.get(key).get('name')+"'s Indicators"}</p>)
      playersById.get(key).get('indicators').forEach(function(value, key2, map){
          indic_list.push(<Indicator playerId={key} action={this.props.modIndicator} label={key2}>{value}</Indicator>)
      }, this);
    },this);

    //Collections
    collections.forEach(function(value, key, map) {
      coll_list.push(<span>{key}: {collections.get(key).get("content").size}</span>);
      collections.get(key).get("control").forEach(function(value, key, map){
          coll_list.push(<span>Control: {value}</span>);
      });
    });

    return (
        <div className="frame">
          <div className="left-col">
            {indic_list}
          </div>
          <div className="center-col">
            <span className="collections">
              {coll_list}
            </span>
            <div id="gameboard"></div>
          </div>
          <div className="right-col">
            <div className="counters">
              {counters.map(function(type){
                return <Counter label={type}>????</Counter>
              })}
            </div>
          </div>
        </div>
      )
  }
}
Game.PropTypes = {
  playersById:  PropTypes.object.isRequired,
  collections: PropTypes.object.isRequired,
  counters: PropTypes.object.isRequired,
  modIndicator: PropTypes.func.isRequired
}
function mapStateToProps(state) {
  return {
    playersById: state.get('playersById') || new List(),
    collections: state.get('collections') || new List(),
    counters: state.get('counters') || new List()
  };
}
export const GameContainer = connect(mapStateToProps, actionCreators)(Game);

编辑2解决方案我的问题的解决方案来自这个线程。获取React中组件的高度 https://stackoverflow.com/questions/35915257/get-the-height-of-a-component-in-react

以下是我的代码中的实现。

import React, {PureComponent, PropTypes} from 'react';
// import Card from '../../Components/Card/index.js';
// import Collection from '../../Components/Collection/index.js';
import {List} from 'immutable';
import Indicator from '../../Components/Indicator/index.js';
import Counter from '../../Components/Counter/index.js';
import {connect} from 'react-redux';
import * as actionCreators from './../../action_creators.js';
import './styles.scss';

export default class Game extends PureComponent {
  render() {
    let playersById = this.props.playersById;
    let collections = this.props.collections;
    let counters = this.props.counters;

    let indic_list = [];
    let coll_list = [];

    //Indicators
    playersById.forEach(function(value, key, map){
      indic_list.push(<p className="section-name">{playersById.get(key).get('name')+"'s Indicators"}</p>)
      playersById.get(key).get('indicators').forEach(function(value, key2, map){
          indic_list.push(<Indicator playerId={key} action={this.props.modIndicator} label={key2}>{value}</Indicator>)
      }, this);
    },this);

    //Collections
    collections.forEach(function(value, key, map) {
      coll_list.push(<span>{key}: {collections.get(key).get("content").size}</span>);
      collections.get(key).get("control").forEach(function(value, key, map){
          coll_list.push(<span>Control: {value}</span>);
      });
    });

    return (
        <div className="frame">
          <div className="left-col">
            {indic_list}
          </div>
          <div className="center-col">
            <span className="collections">
              {coll_list}
            </span>
            <div id="gameboard" ref={(node) => this.calcHeight(node)}></div>
          </div>
          <div className="right-col">
            <div className="counters">
              {counters.map(function(type){
                return <Counter label={type}>????</Counter>
              })}
            </div>
          </div>
        </div>
      )
  }
  calcHeight(node){
    if (node) {
        console.log("calcHeight", node.getBoundingClientRect());
      }
  }
}
Game.PropTypes = {
  playersById:  PropTypes.object.isRequired,
  collections: PropTypes.object.isRequired,
  counters: PropTypes.object.isRequired,
  modIndicator: PropTypes.func.isRequired
}
function mapStateToProps(state) {
  return {
    playersById: state.get('playersById') || new List(),
    collections: state.get('collections') || new List(),
    counters: state.get('counters') || new List()
  };
}
export const GameContainer = connect(mapStateToProps, actionCreators)(Game);

正如我在最终编辑中所述,此问题的解决方案来自此线程。获取React中组件的高度 https://stackoverflow.com/questions/35915257/get-the-height-of-a-component-in-react答案受到 SmokeyPHP 评论的影响,我试图在元素实际渲染之前访问属性。我需要确保事后访问它们以获得准确的信息。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用纯 JavaScript 获取元素的尺寸和位置[重复] 的相关文章

  • 如何设置必须输入特定数字的字段?

    我想知道如何创建一个需要输入特定数字或文本的字段 例如 激活码 以及在输入的确认答案的情况下移动到 网页 并且在未确认的情况下移动到 另一页面 的按钮 使用必需的属性
  • 如何在 JavaScript 中将变量的内容写入文件[重复]

    这个问题在这里已经有答案了 可能的重复 firefox 如何启用本地 JavaScript 来读取 写入我的 PC 上的文件 https stackoverflow com questions 2846045 firefox how to
  • 转义 \u200b(零宽度空格)和其他非法 JavaScript 字符

    我有一组 JavaScript 对象 我引导到后端模板 以在页面加载时初始化我的 Backbone js 集合 它看起来像这样 作为 Twig 模板 我遇到的问题是某些文本字段包含 u200b 零宽度空格 这会破坏
  • 不要包裹 span 元素

    我有一份清单 span 可以在 a 内左右移动的元素 div 元素 如果某些跨度超出了 div 它们应该被隐藏 这可以很好地使用overflow hidden 但是 如果跨度超出了 div 的容纳范围 跨度就会换行 这对于我的用例来说是不期
  • Javascript:我应该隐藏我的实现吗?

    作为一名 C 程序员 我有一个习惯 将可以而且应该私有的东西设为私有 当 JS 类型向我公开其所有私有部分时 我总是有一种奇怪的感觉 而且这种感觉并没有被 唤起 假设我有一个类型draw方法 内部调用drawBackground and d
  • 修改 Twitter 帖子上可编辑 Div 的内容

    我正在编写一个 chrome 扩展 它可以帮助用户在 Twitter 上输入内容 当在 twitter 上写推文时 twitter 会打开一个可编辑的 div 容器 当用户输入内容时 twitter 大概正在使用某些网络框架 会生成子 di
  • 使用 # 时锚点 标签在 Chrome 中不起作用

    这是我在页面上使用的代码 li a href explore Sound Sound a li 在所有页面上出现的菜单中 a a 在我想要链接的页面上 我尝试过使用 id 将内容添加到标签中 但仅在 Chrome 中 浏览器不会向下滚动到该
  • 如何包装内在组件,保留大部分 Props?

    我想用我自己的 React 功能组件包装一个标准按钮 但我希望新组件的用户能够设置 几乎所有底层按钮的道具 当然 我想保持正确的打字 所以如果 WrappedButton 包含一个button then
  • 冒泡可用于图像加载事件吗?

    我可以用吗 window addEventListner 某种程度上来说 我所有的图像都有一个display none 图像加载后 我想设置display inline 这样我就可以规范下载图像时显示的内容 在这种情况下 我无法预加载图像
  • Next.js:错误:React.Children.only 期望接收单个 React 元素子元素

    我有一个名为Nav inside components目录及其代码如下所示 import Link from next link const Nav gt return div a Home a a About a div export d
  • JSONP 使用 JQuery 从 HTTPS 协议获取 JSON

    我正在尝试获取从 https 安全站点发送的 JSON 客户端希望不要使用任何服务器端语言 全部都是 Javascript 我读到 当使用 Jquery 中的 ajax 函数时 我必须使用 JSONP 才能从安全站点加载 JSON 我的第一
  • Riak 在 MapReduce 查询中失败。使用哪种配置?

    我正在与 riak riak js 结合开发一个 nodejs 应用程序 并遇到以下问题 运行此请求 db mapreduce add logs run 正确返回存储在存储桶日志中的所有 155 000 个项目及其 ID logs 1GXt
  • 中有样式表 吗?

    在内部链接 CSS 文件是一个坏主意吗 body 我读过 如果浏览器在外部找到另一个 CSS 文件 则它会被迫重新开始 CSS 渲染 head 只是因为它可能需要将样式应用于已经渲染的元素 另外 我认为 HTML 无法正确验证 我需要确认这
  • jQuery 中什么函数相当于 .SelectMany()?

    让我解释一下 我们知道 jQuery 中的映射函数充当 Select 如 LINQ 中 tr map function return this children first returns 20 tds 现在的问题是我们如何在 jQuery
  • 将 JSON 属性绑定到表单

    我有一个 JSON 对象和一个
  • 减小 TinyMCE 文本区域中的行间距

    I am using TinyMCE to provide a rich text editing text editor But the line spacing between the lines is too much I have
  • Keycloak-js updateToken(minValidity) 需要澄清

    我在Keycloak js中阅读了很多该方法的示例 但没有对以下方法进行明确的解释 updateToken minValidity number KeycloakPromise
  • Jquery 以编程方式更改

    文本

    编辑 解决方案是将其添加到个人资料页面而不是性别页面 profile live pageinit function event p pTest text localStorage getItem gender 我在列表视图中有一个带有一些文
  • 区分 NaN 输入和输入类型为“number”的空输入

    我想使用 type number 的表单输入 并且只允许输入数字
  • HTML 表格 - 固定列宽和多个可变列宽

    我必须建立一个有 5 列的表 表格宽度是可变的 内容宽度的 50 有些列包含固定大小的按钮 因此这些列应该有一个固定大小 例如 100px 有些列中有文本 所以我希望这些列具有可变的列宽 例如 Column1 tablewidth sum

随机推荐