首页 > 解决方案 > 通过 JS 的样式底部和左侧计算不起作用

问题描述

免责声明:我只是忘记了一个属性,正如这里指出的那样https://stackoverflow.com/a/65531072/14824067

我写了一个更大的代码,但为了测试目的,我把它分解成一个测试代码。也许这是一个很小的错误——但我找不到。

你看到我错过了什么吗?

我想做什么:通过 js 设置顶部和底部间隙 - 它应该可以工作 - 我之前做过 - 我只需要在大程序中计算它 - 因此我使用 % 并使用 css “calc”-function

测试代码如下:

       <!doctype html>
        <html lang="en">
            <head>
                <meta charset="utf-8">
                <title>test</title>
            </head>
        
            <body>
                
                <p id="hi">hey</p>
                
                
            </body>
                    <script>
                        document.getElementById('hi').style.display= "block";
                        document.getElementById('hi').style.bottom= "calc( 50% "+" + "+" 20% )";
                        document.getElementById('hi').style.left=   "calc( 50% "+" + "+" 20% )";
                    </script>
        </html>

标签: javascripthtmlcss

解决方案


我不清楚你为什么不想使用 css。

您使用 js 创建的规则只能position: absolute作为选项使用。添加这行js代码来设置绝对定位:

document.getElementById('hi').style.position = "absolute";

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>test</title>
  </head>
<body>
  <p id="hi">hey</p>
</body>
  <script>
  document.getElementById('hi').style.display = "block";
  document.getElementById('hi').style.bottom = "calc( 50% "+" + "+" 20% )";
  document.getElementById('hi').style.left = "calc( 50% "+" + "+" 20% )";
  document.getElementById('hi').style.position = "absolute";
  </script>
</html>


推荐阅读