JS realizes full-screen browsing of pictures with unlimited swiping
Infinite loading strategy
Since it is infinite swiping, it is not possible to get all the pictures to be loaded at the same time; because there must be Scratching effect, so the left and right sides of the current image need to be preloaded. Therefore, you can use three pictures as a window and use the rotation strategy to achieve an infinite swipe list.
<p class="lightbox"> <p class="container"> <p class="lightbox-item prev"></p> <p class="lightbox-item current"></p> <p class="lightbox-item next"></p> </p> </p>
The .lightbox full-screen layout, the .lightbox-item contains the previous, current, and next pictures. Whenever the picture is swiped, we change the next picture to the previous picture, the current picture to the previous picture, the original previous picture as the next picture and preload the next picture resource.
Note that an extra layer of .container is added here and it wraps all images. In this way, when we need the picture to slide as a whole, we can animate it.
Layout style
We set the .lightbox to full screen, put the .prev to the left of the current screen, and .next to the right.
.lightbox, .container .lightbox-item{ position: fixed; left: 0; right: 0; top: 0; background-color: #000; } .container{ position: absolute; } .lightbox-item{ /* 我们用背景图来显示图片 */ position: absolute; background-repeat: no-repeat; background-position: center; background-size: contain; } .lightbox-item.prev{ left: -100%; right: 100%; } .lightbox-item.next{ left: 100%; right: -100%; }
Under some browsers (such as a certain Samsung's own browser), it will be found that the page content is actually three times as wide as the page. So the page was widened so that all three pictures were displayed. Setting overflow can fix this problem:
.lightbox{ overflow: hidden; }
Binding touch events
The key to the picture swiping effect lies in the user The touch event can be directly bound to the window because it is full-screen browsing. But when binding to window, we have to pay attention to conflicts and binding issues. You can .off the function you registered, or you can add a namespace, for example:
$(window) .on('mouseup.lightbox touchend.lightbox', onTouchEnd) .on('mousemove.lightbox touchmove.lightbox', onTouchMove) .on('mousedown.lightbox touchstart.lightbox', onTouchBegin) $(window) .off('mouseup.lightbox touchend.lightbox') .off('mousemove.lightbox touchmove.lightbox') .off('mousedown.lightbox touchstart.lightbox')
There are 6 The key events are:
## mousedown, mousemove, mouseup: mouse press, move and relax;
touchbegin, touchmove, touchend: touch press, move and leave.
Picture sliding animation
In fact, the picture is not animated as the finger moves, just Just update its position when touchmove.
// 起始位置,划动距离 var beginX, translateX; function onTouchBegin(e){ beginX = getCursorX(e); } function getCursorX(e) { // 如果是鼠标事件 if (['mousemove', 'mousedown'].indexOf(e.type) > -1) { return e.pageX; } // 如果是触摸事件 return e.changedTouches[0].pageX; } function onTouchMove(e){ translateX = getCursorX(e) - beginX; $('.container') .attr('transform:translate3d(' + translateX + ')'); .attr('-webkit-transform:translate3d(' + translateX + ')'); }
The -webkit-transform here is for compatibility with the Android UC browser, and everything else seems to be OK. Also note that translate3d enables hardware acceleration, while translateX does not. Therefore, the performance of translateX in ordinary Android browsers is very poor.
When encountering compatibility issues, I really want to talk about Tiansha’s UC. But then I thought about it, at least it doesn't have to be compatible with IE6, and I don't have to complain too much.
Determining the sliding target
The above code still lacks one onTouchEnd, that is, the user will let go after swiping a certain distance. what happens? If the swipe distance is large enough, then continue the animation and slide to the next picture, otherwise, return to the original position. At the same time, the swiping speed also needs to be detected. If the distance is short but the speed is very large, picture switching should also be performed.
Have we never considered the details here when we usually slide pictures?
Record the start time in onTouchBegin, and in onTouchEnd that is Calculable speed.
var beginTime, endTime; function onTouchBegin(e){ beginTime = Date.now(); } function onTouchEnd(e){ endTime = Date.now(); animateTo(getTarget()); }
Here getTarget() is used to calculate the picture to be swiped, while animateTo calls a swipe animation.
[Code]php code:function getTarget(){
// 首先检测划动距离,返回 -1, 0, 1 表示上一张,当前,下一张
var direction = getDirection(translateX, 0.3 * $(window).width());
// 如果划动距离检测为0,继续检测速度
if (direction === 0) {
var deltaT = Math.max(endTime - beginTime, 1);
var v = translateX / deltaT;
direction = getDirection(v, 0.3);
}
return ['.prev', '.current', '.next'][direction + 1];
}
function getDirection(offset, max) {
if (offset > max) return -1;
if (offset < -max) return 1;
return 0;
}
Copy after login
function getTarget(){ // 首先检测划动距离,返回 -1, 0, 1 表示上一张,当前,下一张 var direction = getDirection(translateX, 0.3 * $(window).width()); // 如果划动距离检测为0,继续检测速度 if (direction === 0) { var deltaT = Math.max(endTime - beginTime, 1); var v = translateX / deltaT; direction = getDirection(v, 0.3); } return ['.prev', '.current', '.next'][direction + 1]; } function getDirection(offset, max) { if (offset > max) return -1; if (offset < -max) return 1; return 0; }
Animation after the stroke ends
After the swipe is completed, we need to slide the .container to the target image. In order to avoid abruptly replacing the current image with the target image, we set the transform animation to the target position and then replace it quietly. The following is the main logic of animateTo:
// 计算划动到的目标图片对应的translateX var translateX = $(window).width() * (1 - idx); $('.container').animate({ 'transform': 'translate3d(' + translateX + 'px, 0px, 0px)' '-webkit-transform': 'translate3d(' + translateX + 'px, 0px, 0px)' }, { duration: 1000, complete: function() { // 动画结束后进行图片轮换 var $wps = $('.container').find('.lightbox-item'); var $prev = $wps.filter('.prev'); var $curr = $wps.filter('.current'); var $next = $wps.filter('.next'); if (target === '.prev') { idx--; $prev.attr('class', 'lightbox-item current'); $curr.attr('class', 'lightbox-item next'); $next.attr('class', 'lightbox-item prev'); prefetch('.prev', idx - 1); } else if (target === '.next') { idx++; $next.attr('class', 'lightbox-item current'); $curr.attr('class', 'lightbox-item prev'); $prev.attr('class', 'lightbox-item next'); prefetch('.next', idx + 1); } $(.container).css('transform', 'none'); $(.container).css('-webkit-transform', 'none'); } });
Remember? We need to pre-fetch the next picture after sliding it. In this way, the picture can be scrolled continuously. The operation of prefetch is to prefetch the next image address from the server, and then replace the oldest image in the sliding window. Its specific implementation is also related to the server, so I won’t go into details here.
注意!当动画结束时对.prev,.current,.next进行轮换并重置transform。 如果重置为translate3d(0,0,0)则动画仍会继续,页面就会跳一下。 如果重置为none则会非常平滑,同时别忘了-webkit-transform来兼容更多浏览器。
TouchBegin 的兼容性
在Android ICS下如果touchbegin和第一个touchmove中都未调用 preventDefault, 后续的touchmove和touchend就不会被触发。 解决办法当然是在onTouchBegin中进行preventDefault(), 然而这样click事件(点击关闭全屏啊!)就不会被触发了:
function onTouchBegin(e) { e.preventDefault(); }
所以我们需要在onTouchMove中来判断这是否是一个Click,并手动触发它的行为。
function onTouchMove(e){ if(isClick()) onClick(); function isClick() { var deltaT = endTime - beginTime; var deltaX = Math.abs(translateX); // 时间很短,并且移动距离很小,那么应该是个点击! return deltaT < 700 && deltaX < 7; } }
图片渐进载入
当网速很慢时,连续划动就可能使得旧的图片显示出来(因为预取请求仍未返回)。 常见的一个实践是:立即使用一个已经载入的图片来作为Placeholder, 当目标图片载入后用它替换掉当前的Placeholder。
function loadImage($img, src){ // 先设置一个Placeholder $img.attr('src', 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=='); // 载入图片到临时变量 var tmp = new Image(); tmp.onload = function(){ // 资源载入后,将资源显示到目标的img $img.src = src; }; tmp.src = src; }
设置背景图与设置src属性一样,均可以使用该策略。浏览器会复用那个资源。
图片到底提示
在第一张图片右划和最后一张图片左划时,应当给出提示。 可以做一张带有提示信息的Placeholder:
$lightbox.attr('style', 'top:0;left:0;right:0;bottom:0;'); $lightbox.append($('<p class="alert-nomore">').html('没有更多了..'));
然后让文字居中:
.lightbox-item .alert-nomore{ position: absolute; text-align: center; bottom: 50%; left: 0; right: 0; color: #777; font-size: 20px; }
The above is the detailed content of JS realizes full-screen browsing of pictures with unlimited swiping. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

How to use PHP and JS to create a stock candle chart. A stock candle chart is a common technical analysis graphic in the stock market. It helps investors understand stocks more intuitively by drawing data such as the opening price, closing price, highest price and lowest price of the stock. price fluctuations. This article will teach you how to create stock candle charts using PHP and JS, with specific code examples. 1. Preparation Before starting, we need to prepare the following environment: 1. A server running PHP 2. A browser that supports HTML5 and Canvas 3

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

How to use JS and Baidu Map to implement map pan function Baidu Map is a widely used map service platform, which is often used in web development to display geographical information, positioning and other functions. This article will introduce how to use JS and Baidu Map API to implement the map pan function, and provide specific code examples. 1. Preparation Before using Baidu Map API, you first need to apply for a developer account on Baidu Map Open Platform (http://lbsyun.baidu.com/) and create an application. Creation completed

Overview of how to use JS and Baidu Maps to implement map click event processing: In web development, it is often necessary to use map functions to display geographical location and geographical information. Click event processing on the map is a commonly used and important part of the map function. This article will introduce how to use JS and Baidu Map API to implement the click event processing function of the map, and give specific code examples. Steps: Import the API file of Baidu Map. First, import the file of Baidu Map API in the HTML file. This can be achieved through the following code:

How to use JS and Baidu Maps to implement the map heat map function Introduction: With the rapid development of the Internet and mobile devices, maps have become a common application scenario. As a visual display method, heat maps can help us understand the distribution of data more intuitively. This article will introduce how to use JS and Baidu Map API to implement the map heat map function, and provide specific code examples. Preparation work: Before starting, you need to prepare the following items: a Baidu developer account, create an application, and obtain the corresponding AP

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.
