wordpress插件_构建WordPress轮播插件:第3部分

wordpress插件

Without styling, the WordPress carousel we’ve built in the first part of this tutorial is just a list of items, but it is at least useful, in the sense that they’re all visible. The CSS we added in part two of this tutorial enhanced the display of the carousel, but now the problem is that only the first item is shown to the user and there’s no way to display the rest of the items.

如果没有样式,我们在本教程的第一部分中构建的WordPress轮播只是项目列表,但是从它们都可见的角度来看,它至少是有用的。 我们在本教程的第二部分中添加CSS增强了轮播的显示,但是现在的问题是,只有第一个项目显示给用户,而无法显示其余项目。

We added arrows to our carousel, to allow the user to navigate between the different items, and now it’s time to make them usable, with a bit of JavaScript.

我们在轮播中添加了箭头,以允许用户在不同的项目之间导航,现在是时候使用一点JavaScript使它们可用。

In the continuation of this tutorial, we’ll learn how to properly include our script, then we’ll write a script that will launch a function which animates the items when the user hits an arrow.

在本教程的继续中,我们将学习如何正确包含脚本,然后编写一个脚本,该脚本将启动一个函数,当用户点击箭头时,该函数会为项目添加动画效果。

链接JavaScript文件 (Linking a JavaScript File)

Here we’ll use JavaScript to make our arrows useful. As for the CSS part, create a new file. I called it carousel.js and placed it in the root of the plugin’s folder.

在这里,我们将使用JavaScript使箭头变得有用。 至于CSS部分,请创建一个新文件。 我将其称为carousel.js ,并将其放置在插件文件夹的根目录中。

We need to indicate to WordPress that we are using the JavaScript file. To do this, we’ll use the wp_enqueue_script() function.

我们需要向WordPress表示我们正在使用JavaScript文件。 为此,我们将使用wp_enqueue_script()函数。

wp_enqueue_script('carousel', plugin_dir_url(__FILE__) . 'carousel.js', array('jquery'), '1.0', true);

The first two parameters are the same as for wp_enqueue_style(). Then we find an array. This array lists the dependencies, the scripts needed by our script to work. I chose to use jQuery to get around the browser compatibility issues so I indicate to WordPress that I want to use it: as we saw in our article about properly including scripts in WordPress, 'jquery' is a recognised value in WordPress.

前两个参数与wp_enqueue_style()相同。 然后我们找到一个数组。 该数组列出了依赖关系,即脚本运行所需的脚本。 我选择使用jQuery来解决浏览器兼容性问题,所以我向WordPress表示我希望使用它:正如我们在文章中所看到的有关在WordPress中正确包含脚本的描述一样'jquery'是WordPress中公认的价值。

The fourth parameter is the version number of the script. It’s not very important here (see the article previously linked for more information), but we needed to use the last parameter and set it to true so that our script will be included in the footer.

第四个参数是脚本的版本号。 这里不是很重要(有关更多信息,请参见前面链接的文章),但是我们需要使用last参数并将其设置为true以便将脚本包含在页脚中。

The advantage of choosing the footer instead of the header is that we can use wp_enqueue_script() wherever we want. We don’t have the constraint of using it before wp_head() as with wp_enqueue_style(). We will then be able to include our script only if it is necessary: only if we display the carousel.

选择页脚而不是页眉的好处是我们可以在任何需要的地方使用wp_enqueue_script() 。 与wp_enqueue_style()一样,我们没有在wp_head()之前使用它的约束。 然后,只有在必要时我们才可以包括脚本:仅当我们显示轮播时。

The best place to put wp_enqueue_script() therefore is in the condition of our display_carousel() function. We will display the carousel only if there are items to display, so we will include our script with the same condition.

因此,放置wp_enqueue_script()的最佳位置是在我们的display_carousel()函数的条件下。 仅当有要显示的项目时,我们才会显示轮播,因此我们将包含条件相同的脚本。

function display_carousel() {
	// …
	// Here we retrieve the links
	// …
	
	if (!empty($links)) {
		wp_enqueue_script(/* parameters listed above */);
		
		// …
		// Display
		// …
	}
}

Now we are ready to edit our JavaScript file.

现在,我们可以编辑我们JavaScript文件了。

我们想做什么? (What Do We Want to Do?)

First we encapsulate all our code in a function. To prevent collisions with other libraries, WordPress disables the use of $ in jQuery. We can enable it again with this function.

首先,我们将所有代码封装在一个函数中。 为了防止与其他库发生冲突,WordPress禁止在jQuery中使用$ 。 我们可以使用此功能再次启用它。

jQuery(function($) {
	// The code we will write must be placed here
});

There are many different ways to make a carousel, even without modifying our HTML code. Here I suggest you move the ul block. It contains all our items in a row so we can move it horizontally to display one or another item by setting its position. See the schema below, already seen in the previous part of this tutorial, to see what we want to do.

制作轮播有很多不同的方法,即使不修改我们HTML代码也是如此。 在这里,我建议您移动ul块。 它连续包含所有项目,因此我们可以通过设置其位置将其水平移动以显示一个或另一个项目。 请参阅本教程前面部分已经看到的以下模式,以了解我们想要做什么。

schema

To move it we will play with its margin-left CSS property. By default it is set to 0 and therefore “display” the first item. The first item is big enough to fill the carousel block and the second item, which is next to it, can’t be seen thanks to the overflow property.

要移动它,我们将使用其margin-left CSS属性。 默认情况下,它设置为0 ,因此“显示”第一项。 第一个项目足够大以填充旋转木马块,而第二个项目(旁边)由于overflow属性而无法看到。

To display the second item, we have to move the ul block to the left, in order to align the left side of the second item with the left side of the carousel block. This can be achieved with a negative left margin. To test what value we need to use we can experiment with some CSS code (which we remove right after, as we don’t need it).

要显示第二个项目,我们必须将ul块向左移动,以便将第二个项目的左侧与轮播块的左侧对齐。 这可以通过负的左边距实现。 为了测试我们需要使用的值,我们可以尝试一些CSS代码(由于不需要,我们会立即删除它们)。

#carousel ul {
	margin-left: -100%;
}

This simple line deserves an explanation. If you test it, you should see that the first item is not displayed, we see instead the second item. You can test another value to better understand what happened. With -50px we move the ul block 50 pixels to the left for example. With the values I showed you in the CSS above, as the carousel has a width of 900 pixels, I can display the second item with a value of -900px.

这条简单的线值得解释。 如果进行测试,您应该看到没有显示第一项,而我们看到了第二项。 您可以测试另一个值以更好地了解发生了什么。 例如,使用-50pxul块向左移动50个像素。 使用我在上面CSS中显示的值,由于轮播的宽度为900像素,因此我可以显示第二个值为-900px

However we can use percentages instead. The advantage is that this percentage is relative to the container. Here “100%” is equal to “900 pixels” so, if we give a value of -100%, we hide the first item and display the second. Using percentages allows you to modify the width of the container without modifying the values of the margin-left property.

但是,我们可以改用百分比。 优点是该百分比相对于容器。 这里的“ 100%”等于“ 900像素”,因此,如果我们给值-100% ,我们将隐藏第一项并显示第二项。 使用百分比可以使您修改容器的宽度,而无需修改margin-left属性的值。

显示其他项目的功能 (The Function to Display Another Item)

First, we’ll write the function which will display another item. This one will accept one parameter, the direction. If we want to display the previous item, this direction must be set to -1 and, if we want to display the next item, it must be set to 1.

首先,我们将编写将显示另一个项目的函数。 这将接受一个参数,即方向。 如果要显示上一项,则必须将方向设置为-1 ,如果要显示下一项,则必须将方向设置为1

function carousel_show_another_link(direction) {
}

我们去哪里? (Where Do We Go?)

To determine the value to be assigned to margin-left, we need to know where we are. There are a number of possible ways to achieve this, and I chose one that uses only the current value of the margin-left property.

为了确定要分配给margin-left ,我们需要知道我们在哪里。 有多种方法可以实现此目的,我选择了一种仅使用margin-left属性的当前值的方法。

var ul = $('#carousel ul');
var current = -parseInt(ul[0].style.marginLeft) / 100;

The first line retrieves the ul block. As we will reuse it later, storing it in a variable is a good idea. The second line can seem a bit weird. The aim is to store an integer representing the current displayed item. The first item will be represented by 0, the second by 1, etc.

第一行检索ul块。 正如我们稍后将重用它一样,将其存储在变量中是一个好主意。 第二行似乎有点怪异。 目的是存储代表当前显示项目的整数。 第一项将由0表示,第二项将由1 ,依此类推。

To achieve this we get the current value of the margin-left property. The problem is that this value is something like -200% and we want a number: to remove the “%” we use the parseInt() function which transforms the value into an integer (e.g. '-200%' becomes -200). As we want a positive integer we add a “minus” sign (e.g. to get 200 from -200), and we divide by 100 to get the value we want (e.g. 2, not 200).

为此,我们获得margin-left属性的当前值。 问题在于该值类似于-200% ,我们想要一个数字:要删除“%”,我们使用parseInt()函数,该函数将值转换为整数(例如'-200%'变为-200 )。 当我们想要一个正整数时,我们添加一个“减号”(例如,从-200获得200 ),然后除以100得到我们想要的值(例如, 2而不是200 )。

You might wonder why we didn’t use ul.css('margin-left') to get the value of the margin-left property. In fact, .css() is a jQuery method and, in our context, seems to be a better idea. The problem is this method won’t give us a percentage. Using the same values as above, if the current item is the third one, the margin-left property is set to -200% while the .css() method will return -1800px. To calculate the current item using this value in pixels, we then need to use the width of the big container, and I prefer using only the ul block.

您可能想知道为什么我们不使用ul.css('margin-left')来获取margin-left属性的值。 实际上, .css()是一种jQuery方法,在我们看来,这是一个更好的主意。 问题是这种方法不能给我们一定的百分比。 使用与上述相同的值,如果当前项是第三项,则margin-left属性设置为-200%.css()方法将返回-1800px 。 要使用此值(以像素为单位)计算当前项目,我们需要使用大容器的宽度,我更喜欢仅使用ul块。

Now we can calculate the index of the item to display, thanks to the direction given in the argument of our function.

现在,由于函数自变量给出的方向,我们可以计算要显示的项目的索引。

var new_link = current + direction;

是否存在新项目? (Does the New Item Exist?)

Before displaying the new item we need to test whether it exists. If new_link is less than or equal to -1, or is greater than or equal to the total number of items, then it does not exist and we can’t display it, so moving the ul block is not a good idea. Note that this test can seem redundant as arrows are not displayed when we can’t go further, but ensuring that something can actually be done is always a good idea.

在显示新项目之前,我们需要测试它是否存在。 如果new_link小于或等于-1或大于或等于项目总数,则它不存在并且我们无法显示它,因此移动ul块不是一个好主意。 请注意,此测试似乎是多余的,因为当我们不能继续前进时,不会显示箭头,但是确保可以实际完成始终是一个好主意。

var links_number = ul.children('li').length;

if (new_link >= 0 && new_link First we get the total number of items, which is the number ofli tags in our list. This number is useful for the condition we described above as we want a positive integer that mustn't be greater than or equal to the number of items (don't forget that we begin with 0 and not 1).

Displaying the New Item

Finally, the block move can be achieved with a single line. We have to calculate the new value of margin-left. To do that, let's think about it. For every "passed" item we have a width of 100% to travel. That way, the new value of margin-left is 100 times the new item position we just calculated, with a minus sign to go to the left.

[js]ul.animate({'margin-left': -(new_link * 100) + '%'});

I chose here to use a jQuery animation, but you are free to create your own, or even modify the settings of this one.

我选择在这里使用jQuery动画,但是您可以自由创建自己的动画,甚至可以修改该动画的设置。

一些更实用的别名 (Some Aliases for a More Practical Use)

We will now create the functions which will be called every time the user clicks on an arrow. These functions don’t require a huge amount of code, as the only thing they do is call the carousel_show_another_link() function with the right parameter. Below is the code for the function which is called when we click a “previous” arrow.

现在,我们将创建将在用户每次单击箭头时调用的函数。 这些函数不需要大量的代码,因为它们唯一要做的就是使用正确的参数调用carousel_show_another_link()函数。 下面是单击“上一个”箭头时调用的函数的代码。

function carousel_previous_link() {
	carousel_show_another_link(-1);
	return false;
}

Note the return false; to prevent the default behavior of our arrows (don’t forget that they are links). That way, the URL won’t change when the user clicks an arrow.

注意return false; 以防止箭头的默认行为(不要忘记它们是链接)。 这样,当用户单击箭头时,URL不会更改。

The function which displays the “next” item is exactly the same, but with 1 as the parameter for carousel_show_another_link(). I chose to call it carousel_next_link().

显示“下一个”项目的函数完全相同,但是carousel_show_another_link()的参数为1 。 我选择将其称为carousel_next_link()

附加活动 (Attaching the Events)

Finally we have to make these functions useful, by attaching the right events to the right elements. We will do that in a new function, called when we can be sure that our elements are created: when the document is loaded.

最后,我们必须通过将正确的事件附加到正确的元素来使这些功能有用。 我们将在一个新函数中做到这一点,当可以确定我们的元素已创建时调用:加载文档时。

$(document).ready(function() {
		// Here we attach the events
	});

We want to attach the carousel_previous_link() function to every “previous” arrow. With the DOM tree of our carousel we can retrieve them easily, in the same way we retrieved them when we wanted to style them in the CSS.

我们想将carousel_previous_link()函数附加到每个“上一个”箭头。 使用轮播的DOM树,我们可以轻松地检索它们,就像我们想要在CSS中对其进行样式设置时检索它们的方式一样。

$('#carousel ul li a.carousel-prev').click(carousel_previous_link);

Then we can attach the carousel_next_link() function to the right arrows (#carousel ul li a.carousel-next) in the same way.

然后,我们可以以相同的方式将carousel_next_link()函数附加到右箭头( #carousel ul li a.carousel-next )。

You can test this code but a bug should appear: the first time the carousel_show_another_link() function is called, the CSS property margin-left for our ul block doesn’t exist, so an error will occur when we try to retrieve its value.

您可以测试此代码,但应该会出现错误:第一次调用carousel_show_another_link()函数时,我们的ul块CSS属性margin-left不存在,因此当我们尝试检索其值时将发生错误。

To prevent this bug we can initialize the value of this property. Still in the function called when the document is ready (before attaching the events for example), add the following line.

为了防止此错误,我们可以初始化此属性的值。 仍在文档准备就绪时调用的函数中(例如,在附加事件之前),添加以下行。

$('#carousel ul').css('margin-left', 0);

This sets the margin-left property of our ul block to 0 as a default. This property will now exist, without moving the block.

这将ul块的margin-left属性默认设置为0 。 现在将存在此属性,而无需移动块。

You can now click away at the arrows, the carousel is finished and it works!

现在,您可以单击箭头,轮播完成,并且可以正常工作!

结论 (In Conclusion)

In this tutorial we walked through building a carousel plugin using the WordPress Links Manager API. It was a good example of use of this API, but also it was a good way to see how to combine PHP, HTML, CSS and JavaScript in a WordPress plugin.

在本教程中,我们逐步完成了使用WordPress Links Manager API构建轮播插件的过程。 这是使用此API的一个很好的例子,但是它也是查看如何在WordPress插件中组合PHP,HTML,CSS和JavaScript的好方法。

In closing, I would say that there are many different ways to build a carousel, even if we keep the HTML code we generated: we could choose different styles, or different ways to write the script. In fact, the script we wrote here is just an example and we could write a totally different one with the same result.

最后,我要说的是,即使我们保留生成HTML代码,也有很多不同的方式来构建转盘:我们可以选择不同的样式或不同的脚本编写方式。 实际上,我们在此处编写的脚本只是一个示例,我们可以编写一个完全不同的脚本,并获得相同的结果。

You can decide for yourself if you like the code we used here. If not, don’t hesitate to edit it!

您可以自己决定是否喜欢我们在此使用的代码。 如果没有,请立即对其进行编辑!

Even if you liked what we did here, you can still enhance the result. For example, visitors must hit the arrows to see other items: you can try to automatically animate the carousel with the function setTimeout().

即使您喜欢我们在这里所做的事情,您仍然可以提高结果。 例如,访问者必须按箭头才能看到其他项目:您可以尝试使用setTimeout()函数自动为轮播设置动画。

If you’d like to see the finished code, or try the plugin for yourself, it is available to download here.

如果您想查看完成的代码,或者自己尝试使用该插件,可以在此处下载

翻译自: https://www.sitepoint.com/building-a-wordpress-carousel-plugin-part-3/

wordpress插件

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值