【问题标题】:Get dimensions and position of an element using pure javascript [duplicate]使用纯javascript获取元素的尺寸和位置[重复]
【发布时间】:2017-04-06 19:24:29
【问题描述】:

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

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

当前样式:

板的大小宽度和高度由以下定义:

width: 100%;
flex-grow:1;

它的容器具有以下属性:

display: flex;
flex-direction: column;

Image of Board

您应该注意实际尺寸为 [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());
}

Output of my attempts

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

EDIT-1

我们得出的结论是,这可能是时间问题。我需要确保在渲染元素后运行检索尺寸和位置的代码。由于我使用的是 react,所以我找到了这个线程,ReactJS - Get Height of an element。这基本上说我需要连接到 React 的组件生命周期方法 componentDidMount() ,该方法在渲染完成后立即运行。你可以在下面看到我的实现。然而,即使有了这个实现,我似乎仍然得到了 body 容器的尺寸,而不是我正在访问的元素。

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

Edit-2 解决方案 我的问题的解决方案来自这个线程。 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);

【问题讨论】:

  • 如果你想让你的 board 成为一个 offsetParent(这样它里面的元素的位置是相对于它而不是 body),你必须给它一个 position: relative,例如
  • 如果您在页面加载后在控制台中实时运行该代码,您会得到不同的结果吗?
  • 如果我实时运行它,我会得到正确的输出。 getBoundingClientRect ClientRect {上:46,右:1058.515625,下:920,左:115.59375,宽度:942.921875…}
  • 可能是时间问题,它需要向下移动代码或从超时/事件处理程序运行
  • 嗯,这可能是问题所在。我正在使用 react 来呈现 UI。你的回答让我找到了这个线程,我认为它可能能够解决我的问题。 stackoverflow.com/questions/35153599/… 他们说它是从容器中获取尺寸的。我需要通过连接到 componentDidMount 来获取渲染后的尺寸。我将对其进行测试并在此处发布结果。谢谢。

标签: javascript css html reactjs


【解决方案1】:

正如我在最后的编辑中所说,这个问题的解决方案来自这个线程。 Get the height of a Component in React 答案受到来自 SmokeyPHP 的 cmets 的影响,我试图在实际渲染元素之前访问属性。我需要确保事后访问它们以获得准确的信息。

【讨论】:

    【解决方案2】:

    您应该使用.offsetWidth.offsetHeight 属性。

    注意它们属于元素,而不是 .style。

    var width = document.getElementById('foo').offsetWidth;
    

    【讨论】:

    猜你喜欢
    • 2015-05-02
    • 2013-08-29
    • 1970-01-01
    • 1970-01-01
    • 2017-04-24
    • 1970-01-01
    • 2013-05-28
    • 2013-03-08
    • 2011-04-22
    相关资源
    最近更新 更多