2017-06-18 32 views
1

我正在學習JavaScript,並試圖做一個簡單的練習:我有一個文本框,並希望用鍵盤控制它。 我的HTML如下(現在,我只是想1方向)在JS中移動一個元素

const myBox = document.querySelector("h1"); 
document.addEventListener('keydown', function (event){ 
    if (event.keyCode == '38'){ 
     myBox.style.top -= 5; 
     console.log("test if it works"); 
    } 
}); 

,我的HTML與控制檯日誌作品

<!DOCTYPE html> 
<html lang="fr"> 
<head> 
    <meta charset="UTF-8"> 
    <title>Tuto</title> 

    <style> 
     h1 { 
      width: 200px; 
      height: 40px; 
      border: 5px solid #BADA55; 
      color: #A28; 
      margin: 0; 
      text-align: center; 
     } 
    </style> 
</head> 
<body> 

    <div><h1>My text</h1></div> 

    <script type="text/javascript" src="main.js"></script> 
</body> 
</html> 

我的檢查測試。所以事件監聽器呢。 但我的箱子不動。我怎樣才能解決它,爲什麼我使用.style.top不正確?

謝謝

+0

如何在移動框的行之前添加'myBox.style.position =「absolute」;? – geokavel

+1

_「['HTMLElement.style'](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style)屬性用於獲取以及設置**內聯樣式當獲取時,它返回一個CSSStyleDeclaration對象,該對象包含該元素的所有樣式屬性列表,併爲在元素的內聯樣式屬性**中定義的屬性指定值。「_ – Andreas

+0

在這種情況下,將位置設置爲「絕對」會使元素的初始位置變得混亂,我認爲您應該使用'relative'。 –

回答

0

要通過改變它的頂部值移動元素,該元素不能有一個靜態的位置(默認)。您需要將位置更改爲absolute, relative, fixed, etc...

獲取當前topleft等...使用Element#getBoundingClientRect,它會給你正確的初始值,並且保存你需要解析的字符串。由於top需要具有單位(px,em等),因此請將px添加到已更改的top

const myBox = document.querySelector("h1"); 
 
document.addEventListener('keydown', function(event) { 
 
    if (event.keyCode == '38') { 
 
    myBox.style.top = myBox.getBoundingClientRect().top - 5 + 'px'; // parse the string to number, subtract 5, and add 'px' 
 
    console.log(myBox.style.top); 
 
    } 
 
});
h1 { 
 
    position: absolute; 
 
    top: 0; 
 
    left: 0; 
 
    width: 200px; 
 
    height: 40px; 
 
    border: 5px solid #BADA55; 
 
    color: #A28; 
 
    margin: 0; 
 
    text-align: center; 
 
}
<div> 
 
    <h1>My text</h1> 
 
</div>

+0

好的,謝謝,在(parseFloat(myBox.style。頂|| 0) - 5 +'px'),爲什麼使用「| 0」? – droledenom

+0

第一次'top'沒有設置,所以我們需要一個默認的0.然而,我不喜歡它,所以我已經將它改爲'Element.getBoundingClientRect()',它獲得了初始值,並且解析數字。見編輯的答案。 –

0

職位性質類似「頂」,「底」,「左」和「右」是行不通的,除非你的元素有屬性「位置」爲「絕對」或「相對」。 在這種情況下,你想要的是在css上添加「position:relative」到你的h1風格。

如果您想了解更多有關,這可以給你一個領先地位https://www.w3schools.com/css/css_positioning.asp:d

0

1,你必須使用沒有常量,因爲你想改變它,它不能修復;

let myBox = document.querySelector("h1"); 

2 - 你有你的元素設置爲絕對位置。因爲頂部物業工作不能在靜態位置

position:absolute; 

3-你必須頂部位置的值轉換爲數字,然後做一些

myBox.style.top = parseFloat(myBox.style.top || 0) - 5 + 'px'; 

看到我的代碼:https://codepen.io/miladfm/pen/dRNLvw

相關問題