更改元素的顺序

发布于 2024-12-09 14:39:29 字数 518 浏览 0 评论 0原文

我正在创建一个浮动宽度的网站。用户在智能手机上使用从全高清分辨率到约 600 像素的屏幕,这似乎是一个不错的主意。这就带来了一个非常有趣的问题。

当用户使用比最佳分辨率更小的分辨率时,页面的高度会增加很多。这意味着更改某些元素(例如某些图像、搜索框或导航)的顺序可能很有用,以使页面更具可读性,而无需太多滚动。

所以我需要能够访问 DOM 并更改某些页面元素的顺序(交换它们)。

假设我有一个列表,需要交换第 1 项和第 2 项。

<ul>
  <li>1</li>
  <li>2</li>
</ul>

我找到了一个解决方案,该解决方案基于使用函数 appendChild 将已有的项元素附加到

    。然而,文本节点存在一个问题,对于更困难的元素结构来说,它变得非常复杂,因为需要再次重新创建整个节点。

您有什么改进建议吗?

I am creating a website of floating width. The users use screens from full HD resolution to some 600px on smart phones it seems a pretty good idea. This brings up a very interesting problem.

When user uses a smaller resolution than is an optimum the page gets a lot more height. This means it might be useful to change order of some elements (for example some image, search box or navigation) to make the page more readable without much need of scrooling.

So I need to be able to access DOM and change order of some page elements (swap them).

Lets say I have an list and need to swap item 1 and 2.

<ul>
  <li>1</li>
  <li>2</li>
</ul>

I found a solution based on appending already items elements to <ul> by using function appendChild. However there is a problem with text nodes and it gets really complicated to do it for more difficult element structure, since the need of recreating it whole again.

Do you have any suggestion to improve it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

热血少△年 2024-12-16 14:39:29

对于这个简单的情况(交换仅有的两个元素),您可以仅使用 appendChild()

(() => {
  const list = document.querySelector("ul");
  list.appendChild(list.firstElementChild);
})();
<ul>
  <li>List-item #1</li>
  <li>List-item #2</li>
</ul>

同一节点不能存在于多个位置;因此,它会从当前位置删除并放置在集合的末尾。

如果你想做更复杂的排序,你可能应该从 childNodes 创建一个数组并变得疯狂:

(() => {
  const frag = document.createDocumentFragment();
  const list = document.querySelector("ul");
  const items = list.querySelectorAll("li");
  const sortedList = Array.from(items).sort(function(a, b) {
    const c = a.textContent,
      d = b.textContent;
    return c < d ? -1 : c > d ? 1 : 0;
  });
  for (let item of sortedList) {
    frag.appendChild(item);
  }
  list.appendChild(frag);
})();
<ul>
  <li>Dogs</li>
  <li>Snakes</li>
  <li>Cats</li>
  <li>Bugs</li>
</ul>

For this simple case (swapping the only two elements), you can just use appendChild():

(() => {
  const list = document.querySelector("ul");
  list.appendChild(list.firstElementChild);
})();
<ul>
  <li>List-item #1</li>
  <li>List-item #2</li>
</ul>

The same node cannot exist in multiple positions; so, it's removed from its current position and placed at the end of the collection.

If you want to do more complicated sorting, you probably ought to create an array from the childNodes and get all crazy:

(() => {
  const frag = document.createDocumentFragment();
  const list = document.querySelector("ul");
  const items = list.querySelectorAll("li");
  const sortedList = Array.from(items).sort(function(a, b) {
    const c = a.textContent,
      d = b.textContent;
    return c < d ? -1 : c > d ? 1 : 0;
  });
  for (let item of sortedList) {
    frag.appendChild(item);
  }
  list.appendChild(frag);
})();
<ul>
  <li>Dogs</li>
  <li>Snakes</li>
  <li>Cats</li>
  <li>Bugs</li>
</ul>

情话已封尘 2024-12-16 14:39:29

在 2018 年(几年前),仅使用 CSS 就可以实现这一点。您的用例将通过以下方式解决:

ul {
  display: flex;
  flex-direction: column;
}

li:nth-child(2) {
  order: -1;
}

In 2018 (and already a few years ago) this is possible with just CSS. Your use case would be solved by something like this:

ul {
  display: flex;
  flex-direction: column;
}

li:nth-child(2) {
  order: -1;
}
南…巷孤猫 2024-12-16 14:39:29

您可以使用 flex 非常轻松地更改 HTML 元素的顺序。

flex order: 0 通过更改 order 值,您可以决定元素在列中出现的位置

const ascButton= document.getElementById('asc')
const decButton= document.getElementById('dec')

//callback function for soring in ascending order
const ascending = (a,b)=> a.innerHTML - b.innerHTML

//callback function for soring in descending order
const descending = (a,b)=> b.innerHTML - a.innerHTML

let currentOrder = ascending

ascButton.addEventListener('click', ()=>{
	currentOrder = ascending
  order()
})


decButton.addEventListener('click', ()=>{
	currentOrder = descending
  order()
})


const order  = function(){
	const ordered = [...document.getElementsByClassName('col')].sort(currentOrder)
  ordered.forEach((elem, index)=>{
  	elem.style.order = index
  })
}


order()
.row{
  display: flex;
  flex-direction: column;
}
.col{
  padding: 20px;
  border: 1px solid gray;
  margin: 5px;
  order:3;
}
<div class="row">
  <div class="col "   id="one">1</div>
  <div class="col "   id="two">2</div>
  <div class="col " id="three">3</div>
  <div class="col " id="ten">10</div>
  <div class="col "  id="four">4</div>
  <div class="col "  id="five">5</div>
</div>

<button id="asc">ASC</button>
<button id="dec">DESC</button>

您可以在这里找到更复杂的实现 https://jsfiddle.net/nijeesh4all/on5rsax8/

You can use flex to change the order of the HTML elements very easily.

flex order: 0 by changing the order value you can decide where in the column the element appears

const ascButton= document.getElementById('asc')
const decButton= document.getElementById('dec')

//callback function for soring in ascending order
const ascending = (a,b)=> a.innerHTML - b.innerHTML

//callback function for soring in descending order
const descending = (a,b)=> b.innerHTML - a.innerHTML

let currentOrder = ascending

ascButton.addEventListener('click', ()=>{
	currentOrder = ascending
  order()
})


decButton.addEventListener('click', ()=>{
	currentOrder = descending
  order()
})


const order  = function(){
	const ordered = [...document.getElementsByClassName('col')].sort(currentOrder)
  ordered.forEach((elem, index)=>{
  	elem.style.order = index
  })
}


order()
.row{
  display: flex;
  flex-direction: column;
}
.col{
  padding: 20px;
  border: 1px solid gray;
  margin: 5px;
  order:3;
}
<div class="row">
  <div class="col "   id="one">1</div>
  <div class="col "   id="two">2</div>
  <div class="col " id="three">3</div>
  <div class="col " id="ten">10</div>
  <div class="col "  id="four">4</div>
  <div class="col "  id="five">5</div>
</div>

<button id="asc">ASC</button>
<button id="dec">DESC</button>

You can find a much more complex implementation here https://jsfiddle.net/nijeesh4all/on5rsax8/

故人的歌 2024-12-16 14:39:29

交换innerHTML 也可以吗?

var myList = document.getElementsByTagName("ul")[0]; 
temp = myList.getElementsByTagName("li")[0].innerHTML;
myList.getElementsByTagName("li")[0].innerHTML = myList.getElementsByTagName("li")[1].innerHTML;
myList.getElementsByTagName("li")[1].innerHTML = temp;

wouldn't swapping innerHTML also work?

var myList = document.getElementsByTagName("ul")[0]; 
temp = myList.getElementsByTagName("li")[0].innerHTML;
myList.getElementsByTagName("li")[0].innerHTML = myList.getElementsByTagName("li")[1].innerHTML;
myList.getElementsByTagName("li")[1].innerHTML = temp;
怪我鬧 2024-12-16 14:39:29

以下代码适用于任意数量的同级,向上或向下移动一个同级。这里,“元素”是您想要与其兄弟元素相比移动的元素。

上移:

function moveUp(element){
    var upperSibling = element.previousElementSibling;
    if(upperSibling === null) return;
    upperSibling.insertAdjacentElement("beforebegin", element);
}

这会在 ("beforebegin") 其前一个同级 (上一个ElementSibling)。

向下移动:

function moveDown(element){
    var lowerSibling = element.nextElementSibling;
    if(lowerSibling === null) return;
    lowerSibling.insertAdjacentElement("afterend", element);
}

这会在 ("afterend") 其下一个同级 (nextElementSibling)。

The following code will work for any number of siblings, to move one sibling up or down. Here, "element" is the element you want to move compared to its siblings.

move up:

function moveUp(element){
    var upperSibling = element.previousElementSibling;
    if(upperSibling === null) return;
    upperSibling.insertAdjacentElement("beforebegin", element);
}

This inserts the element before ("beforebegin") its previous sibling (previousElementSibling).

move down:

function moveDown(element){
    var lowerSibling = element.nextElementSibling;
    if(lowerSibling === null) return;
    lowerSibling.insertAdjacentElement("afterend", element);
}

This inserts the element after ("afterend") its next sibling (nextElementSibling).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文