2017-07-03 28 views
0

嗨,我想我想在編輯我的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> 

回答

1

基本上是因爲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'; 
+0

感謝這最終解決了我的問題。我試圖找出一種方法,不必在另一行添加「px」,但我想這是不能避免的。 – Chef1075

0

你確實錯過了一些至關重要的東西; document.getElementById("box").style.height返回字符串,而不是整數。因此,您不能使用+=

但是,您可以通過用document.getElementById("box").style.height = "300px";之類的內容覆蓋字符串來手動設置高度。

您還可以使用element.offsetHeight做條件爲基礎的調整:

var the_box = document.getElementById("box"); 
 
var offset_height = the_box.offsetHeight; 
 
var new_height = offset_height + 100; 
 
the_box.style.height = new_height + 'px'; 
 

 
// OR 
 

 
document.getElementById("box").style.height = document.getElementById("box").offsetHeight + 100 + 'px';
#box { 
 
    width: 200px; 
 
    height: 200px; 
 
    background-color: black; 
 
}
<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>

請注意,你需要追加px高度的結束,一旦你所做的調整,將其轉換回基於像素的string

希望這會有所幫助! :)

0

document.getElementById().style.width將返回一個有效的長度表達式,就像在線樣式聲明一樣。如果聲明是語法無效的,那麼它將不會返回任何內容。元素的寬度或高度僅在百分比或長度單位有效時纔有效。至於你的情況,你必須解析返回的值。比方說,你可以用parseInt(document.getElementById("box").style.width,10)這個函數來解析它。希望這可以幫到你。

相關問題