子 div 的随机定位有时会溢出父 div。我如何stop/prevent这个?

Random positioning of child div sometimes overflows parent div. How do I stop/prevent this?

每次刷新页面时,child div的定位有时候是overflow或者是自己定位在parent div之外。关于如何防止这种情况的任何想法?我试过 child div 的大小以及它的 "top""left" 值,但没有任何运气。

代码如下:

#box {
            width: 1000px;
            height: 400px;
            background-color: grey;
            margin: 0;
            padding: 0;
        }

        #shape {
            display: none;
            position: relative;
        }

    </style>
</head>
<body>
    <div id="box">
        <div id="shape"></div>
    </div>
    <script>
        function makeShapeAppear() {
            var top = Math.floor(Math.random() * 301);
            var left = Math.floor(Math.random() * 901);
            var size = Math.floor(Math.random() * 101) + 50;
            document.getElementById("shape").style.display = "block"
            document.getElementById("shape").style.top = top + "px";
            document.getElementById("shape").style.left = left + "px";
            document.getElementById("shape").style.width = size + "px";
            document.getElementById("shape").style.height = size + "px";
            document.getElementById("shape").style.backgroundColor = "red";}
</script>
</body>

提前谢谢你。

出现这种情况的原因是因为您没有考虑 child 的随机大小。

var size = Math.floor(Math.random() * 101) + 50;

该行最多可以生成 150 个尺寸。

var top = Math.floor(Math.random() * 301);

该行最多可以设置 300 个。

parent div 只有 400px 高,所以如果尺寸计算为 150,顶部为 300,child 将溢出 parent底部 50px。设置 left 会导致 child 在 parent 的右侧溢出时会发生类似的情况。您需要约束顶部和左侧。示例如下。

function makeShapeAppear() {
    var size = Math.floor(Math.random() * 101) + 50;
    var top = Math.min(Math.floor(Math.random() * 101), 180 - size);
    var left = Math.min(Math.floor(Math.random() * 301), 400 - size);
    
    document.getElementById("shape").style.display = "block"
    document.getElementById("shape").style.top = top + "px";
    document.getElementById("shape").style.left = left + "px";
    document.getElementById("shape").style.width = size + "px";
    document.getElementById("shape").style.height = size + "px";
    document.getElementById("shape").style.backgroundColor = "red";
    
    setTimeout(function() { makeShapeAppear(); }, 1000);
}

makeShapeAppear();
#box {
    width: 400px;
    height: 180px;
    background-color: grey;
    margin: 0;
    padding: 0;
}

#shape {
    display: none;
    position: relative;
}
<div id="box">
    <div id="shape"></div>
</div>