gpt4 book ai didi

javascript - 调整高度和宽度样式;像素值以字符串形式输出

转载 作者:太空宇宙 更新时间:2023-11-04 08:29:39 24 4
gpt4 key购买 nike

您好,当我试图编辑我的 div“框”的大小(宽度和高度)时,我觉得我在这里遗漏了一些重要的东西。

当我想查看“box”div 的高度或宽度值时,我可以使用 getElementById 并找到宽度或高度,它会返回像素值。

document.getElementById("box").style.height
">> 200px"

不错。

但是,如果我想编辑该 DIV 中的像素数,看起来 200px 返回的是一个字符串而不是一个数字,所以我无法添加或减去像素。

`document.getElementById("box").style.height += 200
>>"200px200"

document.getElementById("box").style.height += 200px
>>VM1143:1 Uncaught SyntaxError: Invalid or unexpected token

document.getElementById("box").style.height += "200px"
">>200px200px"`

我错过了什么,我不能编辑这个 div 的宽度和高度?添加和减去像素时是否需要删除“px”?

谢谢,下面是我正在使用的代码。

<!DOCTYPE html>
<html>
<head>
<title>
Day 12 - Functions 2 Computation
</title>

<style>
#box {
width: 200px;
height: 200px;
background-color: black;
}
</style>
</head>

<body>
<div id="group">
<button id="bigger">Bigger</button>
<button id="smaller">Smaller</button>
<hr />
<button id="blue">Blue</button>
<button id="red">Red</button>
<button id="green">Green</button>
<div id="status"></div>
</div>

<div id="box" style="height: 200px; width: 200px"></div> <-- This one is giving me issues

<script type="text/javascript"> </script>
</body>
</html>

最佳答案

基本上是因为 style.height 返回的是字符串而不是 int,所以如果您向其中添加任何数字,就会导致错误。

您可以使用 offsetHeight 来获取元素的高度(减去边距但包括填充)

https://www.w3schools.com/jsref/prop_element_offsetheight.asp

(宽度是offsetWidth,逻辑一样)

https://www.w3schools.com/jsref/prop_element_offsetwidth.asp

所以你的代码是:

var el = document.getElementById("box");
var height = el.offsetHeight;
var newHeight = height + 200;
el.style.height = newHeight + 'px';

关于javascript - 调整高度和宽度样式;像素值以字符串形式输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44876700/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com