2017-06-22 184 views
-1

我想在點擊時創建一個交換按鈕或任何按鈕,標記的位置更改。使用javascript的HTML標記的位置更改

例如,

<p id="1">h11</p> 
<p id="2">h22</p> 
<p id="3">h33</p> 

每當向上按鈕被點擊,就變成

<p id="2">h22</p> 
<p id="1">h11</p> 
<p id="3">h33</p> 

每當用戶單擊向下按鈕,就成了

<p id="1">h11</p> 
<p id="3">h33</p> 
<p id="2">h22</p> 

是否有可能交換標籤的位置?

謝謝!

回答

1

這有點愚蠢,因爲沒有insertAfter方法。

function move(id, direction) { 
 
    let el = document.getElementById(id); 
 
    let next = el.nextElementSibling == null ? null : el.nextElementSibling.nextElementSibling; 
 
    let prev = el.previousElementSibling; 
 

 
    if (direction === 'down') { 
 
    el.parentElement.insertBefore(el, next); 
 
    } else { 
 
    if (prev) el.parentElement.insertBefore(el, prev); 
 
    } 
 
}
<link href="//cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css" rel="stylesheet" /> 
 
<div> 
 
    <div id="1">h11</div> 
 
    <div id="2">h22</div> 
 
    <div id="3">h33</div> 
 
    <div id="4">h44</div> 
 
    <div id="5">h55</div> 
 
    <div id="6">h66</div> 
 
</div> 
 
<button onclick="move('1', 'down')">Down</button> 
 
<button onclick="move('1', 'up')">Up</button>

+0

謝謝!有用 – ANG

0

可以使用柔性盒變化的元素

.flex-container { 
 
    display: flex; 
 
    flex-direction: column; 
 
} 
 

 
.first-item { 
 
    order: 2; 
 
} 
 
.second-item { 
 
    order: 3; 
 
} 
 
.third-item { 
 
    order: 1; 
 
}
<div class="flex-container"> 
 
    <div class="first-item">I'm first</div> 
 
    <div class="second-item">I'm second</div> 
 
    <div class="third-item">I'm third</div> 
 
</div>

的順序,這樣,你需要的唯一修改類的名稱。