CSS interactive picture comparison component

Usually, when we need to compare the situation of a certain place or a certain object in different periods, we usually adopt the form of picture juxtaposition or picture rotation, but such form is not direct and lacks interactivity. In order to solve this problem, we can use interactive picture control to achieve. The main idea is to overlap the two front and back pictures, and the user can freely select the display part of the picture, the effect is as follows:

To achieve this effect, we will use the resize attribute so that it can deform horizontally. In order to prevent the image from pulling and deforming, we use a layer of div to wrap one image and place it on the top of another. This is just to adjust the length of the div box to achieve the change of the image display area.

DOM structure is as follows:

    <div class="slider">

      <img src="pic.jpg" alt="">

      <div>

        <img src="pic.jpg" alt="">

      </div>

    </div>

At the same time, in order to make it more obvious that the picture is interactive and adjustable, we introduce a slider to realize this adjustment.

<input type="range">

CSS style is as follows:

.slider{

  position: relative;

  display: inline-block;

  width: 1280px;

  height:720px;

}

.slider > div{

  position: absolute;

  top:0;left: 0;bottom: 0;

  width: 50%;

  overflow: hidden;

  resize: horizontal;

}

.slider > img{

  display: block;

  filter: sepia(1) saturate(.6);/*Set up the filter to simulate the contrast picture*/

}

.slider input{

  position: absolute;

  left: 0;

  bottom: 10px;

  width: 100%;

  margin: 0;

}

However, such a DOM structure will make the process of adding an interactive comparison chart extremely tedious. We should integrate the nested structure together and use js to dynamically add controls:

New DOM structure:

    <div class="slider">

      <img src="pic.jpg" alt="">

      <img src="pic.jpg" alt="">

    </div>

 

js code is as follows:

$(".slider").each(function(){

  var img = $(this).find('img');

  var img1 = img.eq(0);

  var img2 = img.eq(1);

  var div = document.createElement('div');

  $(div).append(img1);

  var input = document.createElement('input');

  input.type = 'range';

  input.oninput=function(){

    div.style.width = this.value+"%";

  }

  $(this).html("");

  $(this).append(img2);

  $(this).append(div);

  $(this).append(input);

});

Our interactive controls are ready to use.

Tags: Attribute

Posted on Fri, 31 Jan 2020 10:27:36 -0800 by arbitter