A few days ago to do a similar project, the effect is the same as the link in the reference link to take notes for the first time, there are mistakes or deficiencies hope to point out, learn modestly, progress together!

So let’s go through the process

  1. Realize the style
  2. Associate the thumbnail image with the larger image displayed
  3. Realize click the button, jump to swiper jump to the specified page function
  4. Slider page number function
  5. Magnifier function
  6. Added thumbnail search function
  7. Unmagnifying glass, reset thumbnail search

1. Implementation style

Because you have thumbnails, you’re going to use swiper to control each other and the thumbnails and the big ones should be on the same page and I’m going to do this here, show the big ones class read, book-detail thumbnails, z-index thumbnails to show and hide them

Note that swiper displays an error when using display to control the display of thumbnails



Reference SwiperThumbnail control/Swiper mutual control

Normal swiper cannot be used because the thumbnail is shown below

Swiper has a multi-row, multi-column swiper exampleMultiple rows of Slides are distributed



However, after copying the slides from the example, it was found that the slides were arranged vertically as shown below. SlidesPerColumnFill: ‘row’ is needed.

Thumbnail complete code

var lines = Math.ceil($(".gallery-thumbs").find(".swiper-slide").length/3);// The number of thumbnail rows
var galleryThumbs = new Swiper('.gallery-thumbs', {
    slidesPerView: 3.slidesPerColumn : lines,
    slidesPerColumnFill : 'row'.// Align swiper horizontally
    freeMode: true.watchSlidesVisibility: true.watchSlidesProgress: true.observer:true.// Automatically initializes swiper when it modifies itself or its child elements
    observeParents:true.// Swiper is automatically initialized when its parent element is modified
});
Copy the code

2. Associate the thumbnail image with the larger image on display

Refer to the Swiper thumbnail control/Swiper mutual control example above

var galleryTop = new Swiper('.book-swiper', {
    observer:true.// Automatically initializes swiper when it modifies itself or its child elements
    observeParents:true.// Swiper is automatically initialized when its parent element is modified
    thumbs: {
        swiper: galleryThumbs// Associate the larger image with the thumbnail
    },
    // The previous and next buttons
    navigation: {
        nextEl: '.next'.prevEl: '.prev',},// page number display
    pagination: {
        el: '.pagination'.type: 'fraction',}});Copy the code

3. Click the button to jump to the swiper page

// Jump to the first page
$(".read-page").find(".first").click(function () {
    galleryTop.slideTo(0.500.false);// The first parameter is the swiper-Slide index to jump to. The second parameter is the animation time
})
Copy the code

To jump to a specified number of pages, just change the first parameter

4. Slider page number function

The first step is to change the length of the slider according to the page number currently displayed. Listen for swiper status changes



HTML structure:

<div class="progress">
   <div class="swiper-progress">
       <span><a ondragstart="return false;" href="javascript:"></a></span>
   </div>
</div>
Copy the code

Style Code (SCSS)

.progress {
    width: 100%;
    height: rem(8);
    padding: 0 rem(35);
    margin-top: rem(35);
    .swiper-progress {
        position: relative;
        border-radius: rem(4);
        background-color: rgba(204.204.204.5);
        height: 100%;
        span {
            height: rem(8);
            border-radius: rem(4);
            width: 0;
            max-width: 100%;
            background-color: #ccc;
            position: absolute;
            left: 0;
            a {
                width: rem(40);
                height: rem(40);
                border-radius: 50%;
                background-color: # 434343;
                border: rem(8) solid #ccc;
                box-sizing: border-box;
                position: absolute;
                right: 0;
                top: 50%;
                transform: translate(50%, -50%); }}}}Copy the code

Js code:

// Add it to either of the two swipers. Since it is related to each other, it can monitor any swiper
on: {slideChange: function(){
        // The slider displays the effect
        // The current number of pages divided by the total number of pages to get the slider width percentage
        var spanWidth = (this.activeIndex + 1) / bookLength * 100+"%";
        $(".swiper-progress span").css("width", spanWidth); }},Copy the code

So far, the page number has been changed, and the slider will also change the function, so how about touching and sliding the page number? You need to use touch listening events on the mobile side, touchStart, TouchMove and TouchEnd to define a few objects

var circular = document.querySelector('.swiper-progress a');/ / the slider
var startX = 0;// Touch screen start coordinates
var x = 0;
var divWidth = $(".swiper-progress span").width();// The original width of the element
Copy the code

Next comes the listening event

// Get the initial position of the current touch screen and the initial position of the element div
circular.addEventListener('touchstart'.(e) = > {
    startX = e.targetTouches[0].pageX;
    x = circular.offsetLeft;
})
// Get the current touch position to calculate the mouse initial position to the current position of the coordinates
circular.addEventListener('touchmove'.(e) = > {
    var moveX = e.targetTouches[0].pageX - startX;
    // Change the box width
    $(".swiper-progress span").css("width", divWidth+moveX+x);
    // Disable the default screen scroll event
    e.preventDefault();
})
circular.addEventListener('touchend'.(e) = > {
    // Get the latest slider width divided by the total width of the progress bar times the total number of pages to get the current number of pages
    // Here I'm worried that the final number will have a decimal point, so round it to the nearest page
    var newIndex = Math.round($(".swiper-progress span").width() / $(".swiper-progress").width() * bookLength);
    galleryTop.slideTo(newIndex - 1.500.false);
})
Copy the code

5. Magnifier function

Click the button to enlarge the image and lock swiper’s default slide event. Click again to restore the size and position of the picture and restore the default swiper event

$(".magnifier").click(function() {$(this).toggleClass("focus");
    $(".book-swiper").toggleClass('swiper-no-swiping');
    if($(this).hasClass("focus")) {$(".book-swiper .swiper-slide-active").find("img").css('transform'.'translate(-50%, -50%) scale(1.5)');
    }else{$(".book-swiper .swiper-slide-active").find("img").css({'transform':'translate(-50%, -50%) scale(1)'.'left':'50%'.'top':'50%'}); }});Copy the code

Drag pictures also listen for finger touch events on the screen, see the slider page function

// Define the image to drag
var magnifierDiv = document.querySelector('.book-swiper .swiper-slide-active img');
// Get the coordinates of finger clicks on the screen
magnifierDiv.addEventListener('touchstart'.(e) = > {
    startX = e.targetTouches[0].pageX;
    startY = e.targetTouches[0].pageY;
    x = magnifierDiv.offsetLeft;
    y = magnifierDiv.offsetTop;
})
// Monitor finger movement to redefine image coordinates
magnifierDiv.addEventListener('touchmove'.(e) = > {
    // Note the condition here to move the image when it is enlarged. Otherwise, when unzooming, swipe the screen and the picture will be dragged
    if($(".magnifier").hasClass("focus")) {
        let moveX = e.targetTouches[0].pageX - startX;
        let moveY = e.targetTouches[0].pageY - startY;
        // Move the box
        magnifierDiv.style.left = x + moveX + 'px';
        magnifierDiv.style.top = y + moveY + 'px';
        // Disable the default scroll evente.preventDefault(); }})Copy the code

6. Add thumbnail search

On the reference page, the click on the thumbnail page also has a search box that allows you to enter a number and displays only the number of pages searched. Here I did this by swiper-sliding through the thumbnails, sifting out the page numbers and hiding the rest of the sibling elements

// Thumbnail search
$(".search .submit").click(function() {
    var searchVal = $(".search input").val();// Get the value in the input box
    $(this).toggleClass("focus");// Search and cancel search switch
    if ($(this).hasClass("focus")) {$(".swiper-box .swiper-slide").each(function(index){
            if (searchVal == index + 1) {
                console.log($(this).find("p").text());
                $(this).siblings().hide(); }}); }else {
        cancelSearch();// Cancel the search}})Copy the code

7. Unmagnify and reset thumbnail search

Because unmagnifying and unsearching are used in multiple places, I’ve encapsulated several methods

// Cancel the search
function cancelSearch() {$(".search input").val("");// Clear the values in the input box
    $(".swiper-box .swiper-slide").show();// Display all elements
    $(".search .submit").removeClass("focus");
}
// Cancel the magnifying glass
function cancelMagnifier() {$(".book-swiper .swiper-slide-active").find("img").css({'transform':'translate(-50%, -50%) scale(1)'.'left':'50%'.'top':'50%'});
    $(".book-swiper").removeClass("swiper-no-swiping");// Restore the default swiper event
    (".magnifier").removeClass("focus");
    $(".swiper-box .swiper-slide").show();
    // Update swiper. If this is not added, the thumbnail style may have problems
    galleryThumbs.update();
    cancelSearch();
};
Copy the code

Add click the slider to turn pages at any position

The principle is the same as the above slider, get the leftmost distance from the slider and click the screen coordinate position, and the total number of pages multiplied by the total number of pages to get the current number of pages should jump, directly on the code.

var lines = document.querySelector('.progress');// Div of the slider
var startX = 0;var linesOffsetX = 0;
// Click the slider to turn the page
lines.addEventListener('touchstart'.(e) = > {
    startX = e.targetTouches[0].pageX;
    linesOffsetX = lines.offsetLeft;
    var newIndex = Math.round((startX - linesOffsetX ) / $(".swiper-progress").width() * bookLength);
    galleryTop.slideTo(newIndex - 1.500.false);/ / page
});
Copy the code

The last

When testing on a real phone, it is found that the thumbnail will hide other adjacent elements and the style will be distorted. Mobile debugging on PC side does not

Finally, I went to the web version of the real machine debugging to find the problem



Disordered style

Add width:100%! important; It is ok

reference

Swiper Demo swiper Chinese API cloud authentic machine