响应式轮播_角度2的响应式轮播组件

响应式轮播

Update (March 22, 2016): Provided a Demo Link which is available on PlunkerUpdate (March 21, 2016): Updated a poorly formatted markdown. Angular 2 instead of [Angular 2]{(https://angular.io)

更新(2016年3月22日) :提供了演示链接,可在Plunker 更新中使用(2016年3月21日) :更新了格式较差的markdown。 Angular 2而不是[Angular 2] {( https://angular.io

The web is growing. It is growing so damn fast that if you don't catch up you might not be able to shine bright in your career as a web developer.

网络正在增长。 它发展得如此之快,以至于如果您不赶上它,您可能就无法在作为Web开发人员的职业生涯中大放异彩。

A few months ago I started hearing about Web Components from the mouths of so-called professional developers. I knew it was one of those new things that "I don't really need now, but I must learn it for the future". Unfortunately, for poor me, Angular, which has always been my favorite JavaScript framework, decided to componentize everything.

几个月前,我开始从所谓的专业开发人员那里听说Web组件 。 我知道这是“我现在真的不需要,但我必须为将来学习”的新事物之一。 不幸的是,对于可怜的我来说,一直是我最喜欢JavaScript框架的Angular决定将所有内容都进行组件化

什么是Web组件? ( What are Web Components? )

This concept is one of the standards of the web that can boast of being easy to grasp.

这个概念是网络的标准之一,可以说易于掌握。

Basically, web components give room for you to simply bundle these tags with its styles and scripts as a reusable component which is exposed via one tag (instead of littering your HTML with similar confusing tags).

基本上,Web组件为您提供了空间,可以将这些标记及其样式和脚本简单地捆绑在一起,作为可重用的组件,该组件通过一个标记公开(而不是用类似的令人困惑的标记来填充HTML)。

A component is basically just a grouping of HTML/JS/CSS all in one.

一个组件基本上只是一组HTML / JS / CSS。

Angular 2进入哪里? ( Where Does Angular 2 Come In? )

Web Components are a new standard that will be here to stay because it is widely accepted. The problem is that we web devs know how this new stuff rolls.

Web组件是一个新标准,因为它已被广泛接受,因此将一直存在。 问题是我们的Web开发人员知道这些新东西是如何滚动的。

Web Components is widely accepted, but not widely supported on browsers, and this is where Angular 2 comes in.

Web组件已被广泛接受,但在浏览器中不受广泛支持 ,这就是Angular 2的用武之地。

Angular 2 is the "new guy". It implements components at its core and makes it simple to work with components in our daily web projects.

Angular 2是“新手”。 它以组件为核心,使在我们的日常Web项目中使用组件变得简单。

I understand that the reason why a lot of us have yet to embrace this "new guy" is because learning Angular 1 was not fun and now we are hearing of another version with a different concept. The good news is Angular 2 is actually simple and you just need 4-5 days to start doing wonders with it.

我知道我们很多人尚未拥抱这个“新手”的原因是因为学习Angular 1并不有趣,现在我们听到的是另一个版本的概念不同。 好消息是Angular 2实际上很简单,您只需要4-5天就可以开始创造奇迹。

Now enough talking (folks hate that these days). Let's have a little fun making a CSS based (and I really mean CSS based) carousel component with Angular 2.

现在有足够的谈话(这些天人们讨厌)。 让我们玩一点乐趣,用Angular 2制作一个基于CSS(我的意思是基于CSS)的轮播组件。

设置Angular 2 ( Setting Up Angular 2 )

npm has become so popular that, recently, tutorials forget to remind us to install them. Therefore, kindly install Node so as to get its package manager, npm.

npm变得如此流行,以至于最近,教程忘记提醒我们安装它们。 因此,请安装Node以获得其软件包管理器npm。

Create a folder in your favorite directory. This will be located probably in your projects folder or desktop. Name it angular2-carousel-component. Navigate via your CLI to this created folder.

在您喜欢的目录中创建一个文件夹。 这可能位于您的项目文件夹或桌面中。 将其命名为angular2-carousel-component 。 通过您的CLI导航到此创建的文件夹。

Create package.json and tsconfing.json at the root of the folder with the following contents:

在文件夹的根目录中创建package.jsontsconfing.json ,其内容如下:

package.json:

package.json:

{
  "name": "angular2-quickstart",
  "version": "1.0.0",
  "scripts": {
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "lite": "lite-server",
    "start": "concurrent \"npm run tsc:w\" \"npm run lite\" "
  },
  "license": "ISC",
  "dependencies": {
    "angular2": "2.0.0-beta.0",
    "systemjs": "0.19.6",
    "es6-promise": "^3.0.2",
    "es6-shim": "^0.33.3",
    "reflect-metadata": "0.1.2",
    "rxjs": "5.0.0-beta.0",
    "zone.js": "0.5.10"
  },
  "devDependencies": {
    "concurrently": "^1.0.0",
    "lite-server": "^1.3.1",
    "typescript": "^1.7.3"
  }
}

tsconfig.json

tsconfig.json

{
  "compilerOptions": {
    "target": "ES5",
    "module": "system",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false
  },
  "exclude": [
    "node_modules"
  ]
}

The tsconfig.json file is a configuration file for TypeScript (more on that later) which the properties are explained here in the "Appendix: TypeScript configuration" section. We can go ahead and install the dependencies by running:

tsconfig.json文件是其中性质解释了打字稿一个配置文件(稍后更多) 这里的“附录:打字原稿配置”部分。 我们可以继续运行以下命令来安装依赖项:

npm install

Add two more folders, app and images. Our main application codes will be in the app folder, but you can copy the images for the slides here into the images folder.

再添加两个文件夹, appimages 。 我们的主要应用代码位于app文件夹中,但是您可以在此处将幻灯片的images复制到images文件夹中。

We are all set to make our component, but before we do that, let us explain the CSS based carousel and how it is implemented.

我们已经准备好制作我们的组件,但是在执行此操作之前,让我们解释一下基于CSS的轮播及其实现方式。

Many of us opt for optimization, right?

我们许多人选择优化,对吧?

Carousels are one of the most popular concepts in the web, but it has its own price. There are heavy images to display and scripts to manipulate the image slides.

轮播是网络上最受欢迎的概念之一,但它有其自身的价格。 需要显示大量图像,并使用脚本来操纵图像幻灯片。

How about we just endure only the pain caused by these images and leave out the troubles of JS? How about we make a Carousel with just CSS? How possible is that?

我们只忍受这些图像所带来的痛苦,而又省去了JS的麻烦,那又如何呢? 我们只用CSS做一个旋转木马怎么样? 那怎么可能呢?

Actually making Carousels has never been easy until I read Harry Roberts article on his blog. Before you get so excited about this simplicity, be sure that your Carousel will be dead simple and basic, and won't have much controls. Just be rest assured that it will be a RESPONSIVE "carousel".

直到我阅读哈里·罗伯茨(Harry Roberts)在他的博客发表的文章时,实际上制作Carousels从未如此轻松。 在对这种简单性感到兴奋之前,请确保您的“旋转木马”将变得简单而基本,并且没有太多控件。 请放心,这将是响应式的 “轮播”。

Assuming we have a template as shown below:

假设我们有一个如下所示的模板:

<div class="carousel">

  <ul class="slides">

    <li>
      <h2>We are covered</h2>
      <img src="images/covered.jpg" alt="">
    </li>

    <li>
      <h2>Generation Gap</h2>
      <img src="images/generation.jpg" alt="">
    </li>

    <li>
      <h2>Potter Me
      <img src="images/potter.jpg" alt="">
    </li>

    <li>
      <h2>Pre-School Kids</h2>
      <img src="images/preschool.jpg" alt="">
    </li>

    <li>
      <h2>Young Peter Cech</h2>
      <img src="images/soccer.jpg" alt="">
    </li>

  </ul>

</div>

Harry's idea is to make the .slides wrapper have a width that is equal to number of slides multiplied by the viewport. So, assuming our viewport is 100% and we have 5 items, the slides width should be 500% so as to contain all the slides when aligned horizontally.

哈里的想法是使.slides包装器的宽度等于幻灯片数量乘以视口。 因此,假设我们的视口为100%并且有5个项目,则幻灯片宽度应为500%,以便在水平对齐时包含所有幻灯片。

We may leave the CSS implementation for now and see it while making the carousel component.

我们可能暂时不使用CSS实现,并在制作轮播组件时看到它。

捆绑在一起 ( Tying Everything Together )

Angular 2 uses Typescript, which from a general perspective is a semi-language that compiles to JavaScript. It implements everything JS, but just gives that feel of strictness which C based languages have that JS does not have. Don't be overwhelmed, it is just a "cool JavaScript".

Angular 2使用Typescript ,从一般角度来看,它是一种可编译为JavaScript的半语言。 它实现了JS的所有内容,但仅给出了JS不具备的基于C的语言所具有的严格性。 不要不知所措,这只是一个“很酷JavaScript”。

Microsoft has a TypeScript plugin for Sublime which will help you with hinting, syntax highlighting and many other of those goodies

微软有一个Sublime的TypeScript插件,它将帮助您进行提示,语法突出显示以及许多其他这些功能。

There are also many other TypeScript plugins for various editors which makes using TypeScript easy no matter what environment you work in.

还有许多其他适用于各种编辑器的TypeScript插件 ,无论您在什么环境下工作,都可以轻松使用TypeScript。

As the idea is to make strict applications, let us first define an interface for the images collection. The interface is just like in any another language, it is a signature which we must adhere to if we care to use it. In the app folder, add a file named image.interface.ts:

因为要严格应用,所以让我们首先为图像收集定义一个接口。 该接口就像任何其他语言一样,它是一个签名,如果我们愿意使用它,则必须坚持该签名。 在app文件夹中,添加一个名为image.interface.ts的文件:

export interface Image {
  title: string;
  url: string;
}

NOTE: You do NOT have to understand what interfaces are before you can follow this tutorial

注意 :您不必了解哪些接口,你可以按照本教程之前,

We just exported an Image Interface which will serve as a signature for the collection of our images. This is typically saying that if you want to make an image collection that implements that interface, it must have a title and url property of type string.

我们刚刚导出了一个图像接口,该接口将用作图像收集的签名。 这通常是说,如果要制作实现该接口的图像集合,则它必须具有string类型的titleurl属性。

Now that we have a signature, we can go ahead and create the carousel component. Create carousel.component.ts in the app directory:

现在我们有了签名,我们可以继续创建轮播组件。 在app目录中创建carousel.component.ts

// Import Component form the angular core package
import {Component} from 'angular2/core';

// Import the Image interface
import {Image} from './image.interface';

// Compoent Decorator
@Component({
  //Name of our tag
  selector: 'css-carousel',
  //Template for the tag
  template: `
 <div class="carousel">

  <ul class="slides">

    <li *ngFor="#image of images">
      <h2>{{image.title}}</h2>
      <img src="{{image.url}}" alt="">
    </li>

  </ul>

</div>
  `,
  //Styles for the tag
  styles: [`
.carousel{
    overflow:hidden;
    width:100%;
}
.slides{
    list-style:none;
    position:relative;
    width:500%; /* Number of panes * 100% */
    overflow:hidden; /* Clear floats */
        /* Slide effect Animations*/
    -moz-animation:carousel 30s infinite;
    -webkit-animation:carousel 30s infinite;
    animation:carousel 30s infinite;
}
.slides > li{
    position:relative;
    float:left;
    width: 20%; /* 100 / number of panes */
}
.carousel img{
    display:block;
    width:100%;
    max-width:100%;
}
.carousel h2{
    margin-bottom: 0;
    font-size:1em;
    padding:1.5em 0.5em 1.5em 0.5em;
    position:absolute;
    right:0px;
    bottom:0px;
    left:0px;
    text-align:center;
    color:#fff;
    background-color:rgba(0,0,0,0.75);
    text-transform: uppercase;
}

@keyframes carousel{
    0%    { left:-5%; }
    11%   { left:-5%; }
    12.5% { left:-105%; }
    23.5% { left:-105%; }
    25%   { left:-205%; }
    36%   { left:-205%; }
    37.5% { left:-305%; }
    48.5% { left:-305%; }
    50%   { left:-405%; }
    61%   { left:-405%; }
    62.5% { left:-305%; }
    73.5% { left:-305%; }
    75%   { left:-205%; }
    86%   { left:-205%; }
    87.5% { left:-105%; }
    98.5% { left:-105%; }
    100%  { left:-5%; }
}
  `],
})
//Carousel Component itself
export class CSSCarouselComponent {
    //images data to be bound to the template
  public images = IMAGES;
}

//IMAGES array implementing Image interface
var IMAGES: Image[] = [
  { "title": "We are covered", "url": "images/covered.jpg" },
  { "title": "Generation Gap", "url": "images/generation.jpg" },
  { "title": "Potter Me", "url": "images/potter.jpg" },
  { "title": "Pre-School Kids", "url": "images/preschool.jpg" },
  { "title": "Young Peter Cech", "url": "images/soccer.jpg" } 
];

When we ran the npm install command, we pulled the angular 2 package into our folder. The first line is importing the angular core library. We also imported the Image interface that we created earlier as we will make use of it here. Notice that we do not have to add the .ts extension when importing.

当我们运行npm install命令时,我们将angular 2软件包放入了我们的文件夹中。 第一行是导入角核库。 我们还导入了之前创建的Image接口,因为我们将在这里使用它。 请注意,导入时我们不必添加.ts扩展名。

The file is exporting a CSSCarouselComponent class which has a public property of an array of images implementing image interface. The class also has a @Component decorator which is specifying the meta-properties of this class. The selector is the name we want the tag to have and the template is the HTML for the component and styles, which is the CSS trick we played to get our carousel working.

该文件正在导出CSSCarouselComponent类,该类具有实现图像接口的图像数组的公共属性。 该类还有一个@Component装饰器,它指定此类的元属性。 选择器是我们希望标签具有的名称,模板是组件和样式HTML,这是我们为使轮播工作而播放CSS技巧。

Note on Angular 2 Stylying Angular 2 supports 3 types of styles which are template-inline, component-inline and external CSS. Just like the normal way, you can add styles directly to template tags which is referred to as template-inline. This is unlike old times, an acceptable practice, because of encapsulation.

关于Angular 2的说明样式 Angular 2支持3种样式,即模板内联,组件内联和外部CSS。 就像通常的方式一样,您可以将样式直接添加到模板标记中,这称为template-inline 。 由于封装,这不同于过去的可接受的实践。

Component-inline is what we just implemented in our demo above while external can be achieved by just replacing the component-inline styles with: [styleUrls: 'style.css']

组件内联是我们在上面的演示中刚刚实现的,而外部可以通过仅用以下方式替换组件内联样式来实现: [styleUrls: 'style.css']

Next up is to create our app component which just serves as a parent. The app component is like the building in the illustration I made while introducing this article. It has the same skeleton as the carousel component. Create app.component.ts in app folder with the following contents:

下一步是创建仅作为父级的app组件。 app组件就像我在介绍本文时所做的插图中的建筑物。 它具有与轮播组件相同的骨架。 使用以下内容在app文件夹中创建app.component.ts

//import Component from angular core
import {Component} from 'angular2/core';

//import our Carousel Component
import {CSSCarouselComponent} from './carousel.component';

//@Component decorator
@Component({
  //tag
  selector: 'my-app',
  //template
  template: `
  <div class="wrapper">
    <css-carousel></css-carousel>
    </div>
  `,  
   //css
  styles: [`
   .wrapper{
      width: 60%;
      margin: 60px auto;
    }
  `],
  //tell angular we are using the css-carousel tag in this component
   directives: [CSSCarouselComponent]
})
//actual class
export class AppComponent { }

The major difference here is the directives property in the @Component decorator which is an array of all the imported components that we will use on this component. Notice we already imported the CSSCarouselComponent after importing angular's core library.

这里的主要区别是@Component装饰器中的directives属性,它是我们将在此组件上使用的所有导入组件的数组。 注意,在导入angular的核心库之后,我们已经导入了CSSCarouselComponent

We can now boot up the app. All there is to do when booting is to import angular, import the app to boot, and boot with the bootstrap() method. Create a file in app with the name boot.ts:

现在,我们可以启动该应用程序。 引导时要做的就是导入angular,导入要引导的应用程序,并使用bootstrap()方法bootstrap() 。 在app创建一个名为boot.ts的文件:

//Import Angular core
import {bootstrap}    from 'angular2/platform/browser'
//Import App Component
import {AppComponent} from './app.component'
//Boot
bootstrap(AppComponent);

As usual, an index.html entry point is needed for our cool app. Create one on the root and update it with:

与往常一样,我们的炫酷应用程序需要一个index.html入口点。 在根目录上创建一个并用以下命令更新:

<!-- head -->
    <title>CSS Carousel Angular 2 Compopnent</title>

    <!-- 1. Load libraries -->
    <!-- #docregion libraries -->    
    <!-- #docregion ie-polyfills -->
    <!-- IE required polyfills, in this exact order -->
    <script src="node_modules/es6-shim/es6-shim.min.js"></script>
    <script src="node_modules/systemjs/dist/system-polyfills.js"></script>
    <!-- #enddocregion ie-polyfills -->

    <script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <script src="node_modules/rxjs/bundles/Rx.js"></script>
    <script src="node_modules/angular2/bundles/angular2.dev.js"></script>
    <!-- #enddocregion libraries -->

    <!-- 2. Configure SystemJS -->
    <!-- #docregion systemjs -->
    <script>
      System.config({
        packages: {        
          app: {
            format: 'register',
            defaultExtension: 'js'
          }
        }
      });
      System.import('app/boot')
            .then(null, console.error.bind(console));
    </script>
    <!-- #enddocregion systemjs -->
<!-- body -->
    <my-app>Loading...</my-app>

Some JS libraries are included, but you should care more about System.js which is a third-party library that adds ES6 module loading functionality across browsers. As seen in the file it helps load our bootstrap file app/boot in the index.html file.

其中包括一些JS库,但是您应该更关心System.js ,这是一个第三方库,可在浏览器中添加ES6模块加载功能。 从文件中可以看出,它有助于将引导文件app/boot加载到index.html文件中。

You can run the app via your CLI wth:

您可以通过以下命令行通过以下方式运行该应用程序:

npm start

最后的话 (Final Words)

Web components is going to trend whether we are ready for it or not. Even if we are to keep trends aside, web components is really an appreciated and accepted concept. Some tools like Polymer and React already started a good job, but if you love angular like me, then Angular 2 is an awesome option.

无论我们是否准备好,Web组件都将成为趋势。 即使我们不考虑趋势,Web组件实际上也是一个值得赞赏和接受的概念。 诸如Polymer和React之类的一些工具已经开始很好地工作,但是如果您喜欢我这样的angular,那么Angular 2是一个很棒的选择。

One last thing, forget the competition among these tools, just stick to what you can afford because they all meet the basic requirements you need to make a web component application.

最后一件事,就是忘记这些工具之间的竞争,而要坚持自己能负担的起,因为它们都满足制作Web组件应用程序所需的基本要求。

翻译自: https://scotch.io/tutorials/responsive-carousel-component-with-angular-2

响应式轮播

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值