首页 > 解决方案 > 无论调整大小如何,如何使移动元素保持一定的高度和宽度?

问题描述

我试图在我的标题中显示移动的单词,并希望无论浏览器大小如何,这些单词都保留在该特定 div 内。我在控制台记录宽度和高度,它似乎保持在参数内,但在页面上它超出了这些范围。我已经尝试过 offSetHeight/Width 和 innerHeight/innerWidth 但这些都不起作用。我正在使用 clientHeight/Width 并且在控制台中有效,但在页面上无效。我已将反弹 div 设置为高度:100vh,宽度设置为 100%。有人能指出我正确的方向吗?

Here is my code:

const bounceDiv = document.querySelector('.bounce')
for (let i = 0; i < words.length; i++) {
    setInterval(function timer() {
        let width = Math.floor(Math.random() * bounceDiv.clientWidth);
        console.log(width + ":" + "width")
        let height = Math.floor(Math.random() * bounceDiv.clientHeight);
        console.log(height + ":" + "height")
        words[i].style.transform = `translate(${width}px, ${height}px) `;
        words[i].style.transition = '1s ease-in-out'
    }, i * 2000);
}

标签: javascripthtmlcss

解决方案


推荐阅读