改变元素的顺序 [英] Changing the order of elements

查看:102
本文介绍了改变元素的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



当用户使用比最佳页面更小的分辨率时,页面获得更多的高度。这意味着更改某些元素(例如某些图像,搜索框或导航)的顺序可能会很有用,以使页面更易于阅读,而不需要进行scrooling。



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



让我说我有一个列表,需要交换项目1和2。

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

我发现了一个基于将已经存在的项目元素添加到< ul> 通过使用函数 appendChild 。然而,文本节点存在问题,因为需要重新创建它,因此需要更复杂的元素结构才会变得非常复杂。



你有没有建议改进它?

解决方案

对于这种简单的情况(只交换两个元素),您可以简单地使用 appendChild()小提琴

  var list = document.querySelector(ul); 
list.appendChild(list.firstElementChild);

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



如果你想做更复杂的排序,你可能应该从childNodes( yaf ),让所有的疯狂:

  var list = document.querySelector(ul); 
var items = list.querySelectorAll(li);
var sortedList = Array.from(items).sort(function(a,b){
var c = a.firstElementChild.textContent,
d = b.firstElementChild.textContent;
返回c d 1:0;
});
for(let sort of sortedList){
list.appendChild(item);
}


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?

解决方案

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

var list = document.querySelector("ul");
list.appendChild(list.firstElementChild);

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 (yaf) and get all crazy:

var list = document.querySelector("ul");
var items = list.querySelectorAll("li");
var sortedList = Array.from(items).sort(function(a, b) {
  var c = a.firstElementChild.textContent,
  d = b.firstElementChild.textContent;
  return c < d ? -1 : c > d ? 1 : 0;
});
for (let item of sortedList) {
  list.appendChild(item);
}

这篇关于改变元素的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆