javascript排序_使用JavaScript对页面内容进行排序

javascript排序

Some of my layout articles, especially those that show items arranged with flexbox or CSS columns, have generated questions about the possibilities of reordering content. While flexbox has the ability to reorder items, the flexbox module is generally intended for changes to UI, rather than reordering based on arbitrary criteria.

我的一些布局文章 ,特别是那些显示使用flexboxCSS列排列的项目的文章 ,引起了有关重新排序内容的可能性的问题。 尽管flexbox可以对项目进行重新排序 ,但是flexbox模块通常用于更改UI,而不是基于任意条件进行重新排序。

In this article, I’ll show how you can easily arrange items alphabetically and chronologically on a page; in turn, you could use the same principles to order items using any kind of criteria.

在本文中,我将向您展示如何轻松地按字母顺序和时间顺序在页面上排列项目 。 反过来,您可以使用相同的原理通过任何类型的条件对商品进行排序。

It’s important to understand that this is true reordering of content, i.e. moving from ABCDE to CBADE. If you want to simply filter content – removing the B & D elements from ABCDE so that the user sees ACE – I’ve shown ways of doing that in previous articles.

重要的是要了解这是对内容的真正重新排序 ,即从ABCDECBADE 。 如果您只想过滤内容-从ABCDE中删除BD元素,以便用户看到ACE-我在前面的 文章中已经介绍了实现此目的的方法。

确定数据源 (Determining The Data Source)

There are four sources of data that we could use to as a key to reorder elements:

我们可以使用四个数据源作为对元素进行重新排序的关键:

  • Use the content: easiest to write HTML for, but slightly tricky to implement, and the hardest to keep consistent. Content keys are used in this example.

    使用内容 :最容易编写HTML ,但是实现起来有些棘手,而且很难保持一致。 在此示例中使用内容密钥。

  • We could use data that already exists in the markup, such as required and their values. This may include information that has been added to the markup, such as data attributes.

    我们可以使用标记中已经存在的数据,例如必需的及其值。 这可能包括已添加到标记中的信息,例如data属性

  • Meta information, such as the file size of images.

    元信息,例如图像的文件大小。
  • We could also use data that exists outside the HTML page, such as a database, when ordering large information sets.

    订购大型信息集时,我们还可以使用HTML页面之外的数据,例如数据库。

To start, I’ll create the markup, enhanced with a little microdata. For this example, I’m using paintings of the French Revolution:

首先,我将创建标记,并添加一些微数据 。 在此示例中,我使用的是法国大革命的画作:

<div id="rev-works">
	<figure itemscope itemtype="http://schema.org/Painting">
		<img src="the-death-of-marat.jpg" alt itemprop="image">
		<figcaption itemprop="name">The Death of Marat</figcaption>
		<div>
			<span itemprop="creator">Jacques-Louis David</span>
			<time itemprop="dateCreated">1793</time>
			</div>
	</figure>
…
</div>

Only one painting is shown here, as all the other works take the same pattern. You can see we have several possible content keys to use, including the date of creation and the artist’s name.

这里仅显示一幅画,其他所有作品都采用相同的图案。 您会看到我们有几个可能要使用的内容密钥,包括创建日期和艺术家的姓名。

CSS (The CSS)

While styling the content isn’t our focus here – there are plenty of ways to place the content side-by-side – this is the basic stylesheet I’m using:

虽然样式并不是我们这里的重点-有很多方法可以并排放置内容-这是我正在使用的基本样式表:

#rev-works,
#rev-works figure div { 
	display: flex;
	align-items: flex-start; 
}
#rev-works figure {
	flex: 1;
	background: #fff;
	padding: 10px; 
}
#rev-works figure img {
	width: 100%;
	height: auto;
}
#rev-works figcaption {
	margin: 1rem auto;
	text-align: center;
	font-weight: 700; 
}
#rev-works figure div {
	justify-content: space-between; 
}

菜单 (The Menu)

We need a UI element to allow the user to sort the content. This could be practically anything, from to buttons, but in this case I’ll use a <select> drop-down:

我们需要一个UI元素,以允许用户对内容进行排序。 从按钮 ,几乎可以是任何东西,但是在这种情况下,我将使用<select>下拉列表

<label for="orderby">Order by:</label>
<select name="orderby" id="orderby">
	<option value="theme">Theme</option>
	<option value="artist">Artist</option>
	<option value="date">Date</option>
</select>

(I’m assuming that the default order of the paintings corresponds to a theme.)

(我假设绘画的默认顺序与主题相对应。)

Ideally the <select> element would be injected into the page with JavaScript, since what we’re about to do requires JavaScript in any case: there’s no point in presenting an element to visitors that they can’t use.

理想情况下, <select>元素将使用JavaScript注入到页面中,因为在任何情况下我们都需要JavaScript:向访问者展示他们无法使用的元素是没有意义的。

JavaScript (The JavaScript)

The basic script is placed at the end of the document:

基本脚本位于文档的末尾:

var theme = document.getElementById("orderby"),
paintings = document.getElementById("rev-works"),
figures = paintings.querySelectorAll("figure"),
original = paintings.innerHTML;
function sortUs(parent, child, key) {
	var items = Array.prototype.slice.call(document.querySelectorAll(parent + " " + child)).sort(function(a, b) {
		var comparA = a.querySelector(key).innerHTML;
		var comparB = b.querySelector(key).innerHTML;
		return (comparA < comparB) ? -1 : (comparA > comparB) ? 1 : 0;
	});
	for (var i = 0; i < figures.length; i++) {
		paintings.appendChild(items[i]);
	}
}
theme.onchange = function(){ 
	if (theme.value == "theme") { 
		paintings.innerHTML = original;
	} else {
		if (theme.value == "artist") { 
			el = "span[itemprop=creator]"; 
		}
	if (theme.value == "date") {
		el = "time"; 
	}
	sortUs("#rev-works","figure",el);
}}

I’m not going to explain every aspect of the code here: that’s for future articles. For now, it’s enough to note the following:

我不会在这里解释代码的每个方面:这是为了以后的文章。 现在,仅需注意以下几点:

  • The central function is the parametrized sortUs, which takes three arguments: the parent element, the children elements to reorder, and the key.

    中心功能是参数化的sortUs ,它采用三个参数:父元素,要重新排序的子元素和键。

  • The original state of the layout is taken at the start of the script so that it can be returned to easily without a re-sort.

    布局的原始状态是在脚本开始时获取的,因此可以轻松地将其返回,而无需重新排序。
  • The innerHTML – that is, the content from a particular element inside each <figure> is taken as the key, and sequentially compared to each other to determine the order of the <figure> elements that contain them.

    innerHTML –即每个<figure>特定元素的内容被用作键,并依次进行相互比较以确定包含它们的<figure>元素的顺序。

There’s one small danger that should be noted: the dates for the paintings are taken and compared as strings, not integers. It works in this case, but if I had a wider range of dates (for example, art from 800 CE) I would definitely need to convert the date keys to true numbers to allow a valid comparison.

应该注意的一个小危险是:绘画的日期是作为字符串而不是整数进行比较的。 它可以在这种情况下工作,但是如果我有较宽的日期范围(例如,公元800年的艺术品),则肯定需要将日期键转换为真数字,以便进行有效比较。

添加轻松 (Adding Easing)

The code works, but the UX is all a little sudden and brutal, with elements appearing and disappearing suddenly. With a little more work you could add a sequential fade-in effect; the code to do that is available in this article’s CodePen repo.

代码可以工作,但是UX有点突然和残酷,元素突然出现和消失。 通过更多的工作,您可以添加顺序淡入效果; 本文的CodePen存储库中提供了执行该操作的代码。

响应与结论 (Responsiveness & Conclusion)

One of the nice aspects of using is that it easily transfers to presenting the paintings in “portrait” mode when the browser window narrows: the script changes the physical order of elements, which flexbox respects.

使用一个不错的方面之一是,当浏览器窗口缩小时,它可以轻松转换为以“肖像”模式呈现绘画:脚本更改了flexbox尊重的元素物理顺序

Hopefully this small piece of code has shown that you don’t necessarily need JQuery or frameworks like IsoTope or TinySort to create dynamic sorted content on your pages.

希望这小段代码表明您不一定需要JQuery或IsoTope或TinySort之类的框架即可在页面上创建动态排序的内容。

翻译自: https://thenewcode.com/905/Sorting-Page-Content-With-JavaScript

javascript排序

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值