使用CSS交换div项目

时间:2019-06-25 11:45:52

标签: javascript html css

div中有两个列表项和一个交换按钮。在交换点击时,我必须更改项目的顺序。我可以使用下面的swap函数来实现它。

var ints = [ "1", "2", "3", "4" ],
    chars = [ "A", "B", "C", "D"],
    list1 = document.getElementById("list1"),
    list2 = document.getElementById("list2"),
    toggle = 0;

setList(list1, ints);
setList(list2, chars);

function setList(element, data) {
  for (var i in data) {  
    var elem = document.createElement("li");
    elem.innerText = data[i];
    element.appendChild(elem);
  }
}

function swap() {
  list1.innerHTML = "";
  list2.innerHTML = "";
  if(toggle==0) {
    setList(list1, chars);
    setList(list2, ints);
    toggle=1;
  } else {
    setList(list1, ints);
    setList(list2, chars);
    toggle=0;
  }  
}
.box {
  display: flex;
  align-items: center;
  position: absolute;
  top: 20px !important;
}
<div class="box">
<ul id="list1"></ul>
<ul id="list2"></ul>
</div>

<button id="btn" onclick="swap()">Swap</button>

我想知道使用CSS是否可以实现此功能。 也可以在Codepen上测试代码https://codepen.io/imjaydeep/pen/EBvaxG?editors=1111

2 个答案:

答案 0 :(得分:1)

使用CSS订单属性实现。

var ints = [ "1", "2", "3", "4" ],
    chars = [ "A", "B", "C", "D"],
    list1 = document.getElementById("list1"),
    list2 = document.getElementById("list2"),
    toggle = 0;

setList(list1, ints);
setList(list2, chars);

function setList(element, data) {
  for (var i in data) {  
    var elem = document.createElement("li");
    elem.innerText = data[i];
    element.appendChild(elem);
  }
}

function swap() {
  if (toggle==0) {
    list1.classList.remove('list1');
    list2.classList.add('list2');
    toggle=1;
  } else {
    list2.classList.remove('list2');
    list1.classList.add('list1');
    toggle=0;
  }  
}
.box {
  display: flex;
  align-items: center;
  position: absolute;
  top: 20px !important;
}

.list1 {
  order: 1;
}

.list2 {
  order: 1;
}
<div class="box">
<ul id="list1"></ul>
<ul id="list2"></ul>
</div>

<button id="btn" onclick="swap()">Swap</button>

答案 1 :(得分:0)

您可以执行以下操作:

用复选框代替按钮,并使用该按钮切换交换,在这种情况下,反转容器div的行顺序

div {
  display: flex;
  align-items: center;
  position: absolute;
}

#swap:checked + div {
  flex-direction: row-reverse;
}
 <label>Swap</label>
 <input type="checkbox" id="swap" />
  <div>
    <ul id="list1">
      <li>1</li>
      <li>2</li>
      <li>3</li>
    </ul>
    <ul id="list2">
      <li>a</li>
      <li>b</li>
      <li>c</li>
    </ul>
  </div>