实现JS代码改变CSS元素

问题描述 投票:0回答:1

这是我的程序的代码摘录,我想知道如何更改它,以便通过在其上方的标签中使用 JS 变量来调整顶部和左侧的值,以便随机化其在 9x9 网格中的位置。我正在用这个制作游戏。

<style>
            #backgroundColor {
                background-color: rgba(211, 233, 254, 0.779);
                margin-top: 5%;
            }

            #content {
                text-align: center;
                width: 100%;
            }
/* I want to change the top and left values to correspond with JS variables. */
            h1 {
                position: absolute;
                top: 1.75%;
                /* Alter values in a grid by 10.75. Make a varible in <script>, go from 1.75-87.75 */
                left: 27.25%;
                /* Alter values in a grid by 5.5. Make a variable in <script>, go from 27.25-71.25 */
                color: rgb(47, 0, 0)
            }

            div {
                position: relative;
                text-align: center;
            }

            image {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
            }
            
            .center {
                display: block;
                margin-left: auto;
                margin-right: auto;
                width: 50%;
            }

            .numbers {
                font-family: monospace;
                font-size: xx-large;
                font-weight: normal;
                font: Menlo;
            }

            .title {
                font-family: monospace;
                font-style: italic;
                font-weight: lighter;
                font-size: xx-large;
            }

            .subtitle {
                font-family: monospace;
                font: Courier;
                font-size: large;
                font-weight: lighter;
            }
        </style>

我尝试使用以下JS代码:

<script type="text/javascript">
    "use strict";
            function getNumCoords(ifX, ifY) {
                const numGridMax = 8;
                var yPos = Math.floor(Math.random()*numGridMax);
                var xPos = Math.floor(Math.random()*numGridMax);
                if (ifX === 1) {
                    return (xPos*5.5)+27.25;
                }
                if (ifX === 1) {
                    return (yPos*10.75)+1.75;
                }
            }
            var outputX = getNumCoords(1, 0) + "%";
            var outputY = getNumCoords(0, 1) + "%";
            var number = document.getElementById("random");
    </script>

为了更改 CSS 元素。

javascript html css variables tags
1个回答
0
投票

这是一个例子。请注意,

left
值必须是字符串,使用模板文字效果很好。

const h1 = document.getElementById("h1");
let left = 0;

function mover() {
  if (left < 100) {
    left += 10;
    h1.style.left = `${left}px`;
  } else {
    clearInterval(interval);
    h1.textContent = "Done";
  }
}
const interval = setInterval(mover, 1000);
h1 {
  color: #008;
  position: relative;
  left: 0;
}
<h1 id="h1">Header</h1>

© www.soinside.com 2019 - 2024. All rights reserved.