并排创建填充的div

时间:2018-04-19 15:14:19

标签: typescript typescript2.0

我正在制作一个带有4个骰子的骰子。我需要得到以下结果: enter image description here

现在我能够实现所有逻辑,但我不知道如何将每个div并排放置并添加ts代码中的黑色填充,现在我得到了:

enter image description here

正如评论中所建议的那样,我创建了一个父div并将其显示样式设置为内联,但没有任何变化,这里是我更新的Die类的代码,它实现了每个die和父div创建:

class Die {
    div: Element;
    value: string;
    text: Element;
    numberSides: number = Object.keys(rolledValues).length / 2;

    constructor(parent: HTMLElement, roll: number) {
        let div: Element = document.createElement('div');
        let value = rolledValues[roll];
        let squareSizeNum: number = 20;
        let squareSize: string = `{ $squareSizeNum }px`;
        (<HTMLElement>div).style.width = squareSize;
        (<HTMLElement>div).style.height = squareSize;
        (<HTMLElement>div).style.padding = '3px';
        let text: Element = document.createElement('p');
        text.textContent = value;
        (<HTMLElement>div).appendChild(text);
        parent.appendChild(div);
        this.div = div
        this.text = text;
    }
}

class DieRoller extends Die {
    constructor(parent: HTMLElement, roll: number) {
        super(parent, roll);
    }
    rollDie() {
        let roll: number = this.getRandomIntInclusive(0, this.numberSides - 1)
        this.text.textContent = rolledValues[roll];
    }

    getRandomIntInclusive: Function = (min, max) => {
        min = Math.ceil(min);
        max = Math.floor(max);
        return Math.floor(Math.random() * (max - min + 1)) + min;
      }
}

let parentDiv: HTMLElement = document.createElement('div')
let numberOfDies: number = 4;
let dies: DieRoller[] = [];
for(let index: number = 0; index < numberOfDies; index++) {
    let dieRoller = new DieRoller(parentDiv, 0);
    dies.push(dieRoller);
    parentDiv.appendChild(dieRoller.div);
}
parentDiv.style.display = 'inline';
document.body.appendChild(parentDiv);

1 个答案:

答案 0 :(得分:0)

You could set the parent/container to use display: flex and justify-content:

.container {
  display: flex;
  justify-content: space-around;
}

Or in your case:

parentDiv.style.display = 'flex';
parentDiv.style.justifyContent = 'space-around';

demo