官术网_书友最值得收藏!

Making an image carousel

Image carousels are among the most popular marketing and showcase tools used on websites. They can also be used to show image galleries or presentations.

In this recipe we're going to build an image carousel. It will support automatic timed transitions that stop if the user moves over the carousel area. It will have a navigation area consisting of control rectangles denoting the currently active images and the number of remaining images.

This will be a 3D carousel utilizing HTLM5 features, such as CSS3 3D transforms.

Getting ready

We will need three images in the directory along with our code. They should be named 1.jpg, 2.jpg, and 3.jpg respectively.

How to do it...

We will be creating the image carousel by using jQuery, HTML5, and CSS transformations.

  1. First, we will create an HTML page with a carousel and the gray image controls. We're going to position the controls in the middle-bottom section of the carousel.
    <!DOCTYPE html>
    <html>
      <head>
        <title>Image carousel</title>
        <style type="text/css">
  2. To get a 3D view that has depth, the main container must have a perspective property. It denotes the distance of the viewer from the screen. It will make nearby things look larger, and distant things look smaller.
    #carousel {
     perspective: 500px;
      -webkit-perspective: 500px;
      position:relative; display:inline-block;
      overflow:hidden;
    }
  3. We're going to place all our images inside the rotator, then rotate the rotator itself. To do this, rotations on the rotator must preserve the 3D transforms of the child elements.
  4. Additionally, both the rotator and the images will have a transition animation. We specify this by adding the transition property. In our example, transitions will work on transforms and will be one second long.
    #rotator {
      transform-style: preserve-3d;
      -webkit-transform-style: preserve-3d;
      position:relative;
      margin:30px 100px;
      width:200px; height:200px;
      transition: transform 1s;
      -webkit-transition: -webkit-transform 1s;
    }
    #rotator img {
      position:absolute;
      width: 200px; height:200px;
      transition: transform 1s;
      -webkit-transition: -webkit-transform 1s;
    }
    #controls {
      text-align: center;
      position:absolute;
      left:0; bottom:0.5em;
      width:100%;
    }
    #controls span {
      height: 1em; width: 1em;
      background-color:#ccc;
      margin: 0 0.5em;
      display: inline-block;
    }
      </style>
    </head>
    <body>
      <div id="carousel">
        <div id="rotator">
          <img class="image" src="1.jpg">
          <img class="image" src="2.jpg">
          <img class="image" src="3.jpg">
          </div>
        <div id="controls"></div>
      </div>
      <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
      <script type="text/javascript" src="example.js">
    </script>
    </body>
    </html>
  5. The code that animates the carousel and makes the controls clickable will be in example.js.
    (function() {
      $("#carousel").on('mouseover', pause);
      $("#carousel").on('mouseout', start);
      var position = 0;
      var all = $("#carousel").find('.image');
      var total = all.length;
  6. We will place all the images in their appropriate position in the 3D space, each one rotated by a multiple of an angle and moved by a calculated amount. For more information see the How it works... section of this recipe.
      var angle = (360 / total);
      var deg2radfac = 2 * Math.PI / 360;
      var zMovement = $("#rotator").width() / 2 *Math.tan(deg2radfac * angle / 2);
      all.each(function(k) {
        var trans = 'rotateY(' + (angle * k).toFixed(0) + 'deg)'
        + 'translateZ('+ zMovement.toFixed(0) + 'px)';
        $(this).css('transform', trans);
      });
      $("#rotator").css('transform', 'translateZ('+ (0 - zMovement).toFixed(0) + 'px)');
  7. For each image we add a control marker, which can activate that image.
    for (var k = 0; k < all.length; ++k) {
      $('<span />').attr('data-id', k).appendTo("#controls");
    }
    $("#controls").on('click', 'span', function() {
      changeTo(position = $(this).attr('data-id'));
    });
    ctrls = $("#controls span");
    start();
  8. Finally, let's write the functions that change the position of the carousel. The change function changes the position by dir elements, and changeTo changes the position directly to the specified element. Then we can start our carousel timer.
    function change(dir) {
      dir = dir || 1;
      position += dir;
        if (position >= all.length) position = 0;
        else if (position < 0) position = 0;
        changeTo(position);
      }
    function changeTo(position, cb) {
      ctrls.css({'opacity': 0.33});
      ctrls.eq(position).css({'opacity': 1});
      $("#rotator").css('transform',
      'translateZ('+ (0 - zMovement).toFixed(0) + 'px) ' +
      'rotateY(' + (angle * position).toFixed() + 'deg) ');
      }
    function start() { timer = setInterval(change, 5000); }
    function pause() {
      if (timer) { clearInterval(timer); timer = null; }
      }
    }());

How it works...

Building our carousel depends on the number of images we're going to use. To get a better sense of what exactly happens when we apply our transforms, lets look at the top view of a carousel. The preceding figure shows a carousel with five sides. Each side is translated away from the center point by a distance z, then rotated by an angle a multiple times. The angle can be calculated as follows: a = 360 / number Of sides.

The translation z however is slightly harder to calculate. To do that, we need to look at the triangle that consists of z and half of the sides width. By applying a trigonometric equation tan(a/2) = (w/2) / z we can calculate z = w/2 / tan(a/2).

To rotate the carousel, we rotate the rotator parent by an angle a every 5 seconds. The user is allowed to click on the controls to change the rotation.

We also move rotator in the opposite direction by z to make the distance of the front element in the carousel the same, as if it hasn't been translated.

We hope that this recipe added some fun and freshness into the slightly dull topic of carousel making, by using some new HTML5 features, which will surely wow the users.

Note

Some of the CSS3 features are not widely available as of this writing. Internet Explorer 9, which otherwise does support a lot of HTML5 doesn't have them, though they're available in Internet Explorer 10. Before using these techniques, review the target browser requirements.

主站蜘蛛池模板: 临清市| 兴文县| 突泉县| 邻水| 建德市| 吴桥县| 南部县| 藁城市| 定日县| 象山县| 台东县| 许昌县| 龙川县| 呼和浩特市| 赣榆县| 古浪县| 隆回县| 南涧| 津市市| 通渭县| 崇文区| 舒兰市| 合作市| 若羌县| 吴桥县| 大洼县| 虞城县| 麻江县| 共和县| 教育| 孝义市| 肇东市| 响水县| 苏尼特右旗| 克山县| 临江市| 涿州市| 拉萨市| 贺兰县| 昌宁县| 随州市|