Home  >  Article  >  Web Front-end  >  JS realizes full-screen browsing of pictures with unlimited swiping

JS realizes full-screen browsing of pictures with unlimited swiping

巴扎黑
巴扎黑Original
2017-05-27 10:46:181480browse

 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(&#39;mouseup.lightbox touchend.lightbox&#39;, onTouchEnd)
    .on(&#39;mousemove.lightbox touchmove.lightbox&#39;, onTouchMove)
    .on(&#39;mousedown.lightbox touchstart.lightbox&#39;, onTouchBegin)
$(window)
    .off(&#39;mouseup.lightbox touchend.lightbox&#39;)
    .off(&#39;mousemove.lightbox touchmove.lightbox&#39;)
    .off(&#39;mousedown.lightbox touchstart.lightbox&#39;)

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 ([&#39;mousemove&#39;, &#39;mousedown&#39;].indexOf(e.type) > -1) {
        return e.pageX;
    }
    // 如果是触摸事件
    return e.changedTouches[0].pageX;
}
function onTouchMove(e){
    translateX = getCursorX(e) - beginX;
    $(&#39;.container&#39;)
        .attr(&#39;transform:translate3d(&#39; + translateX + &#39;)&#39;);
        .attr(&#39;-webkit-transform:translate3d(&#39; + translateX + &#39;)&#39;);
}

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 [&#39;.prev&#39;, &#39;.current&#39;, &#39;.next&#39;][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);
$(&#39;.container&#39;).animate({
    &#39;transform&#39;: &#39;translate3d(&#39; + translateX + &#39;px, 0px, 0px)&#39;
    &#39;-webkit-transform&#39;: &#39;translate3d(&#39; + translateX + &#39;px, 0px, 0px)&#39;
}, {
    duration: 1000,
    complete: function() {
        // 动画结束后进行图片轮换
        var $wps = $(&#39;.container&#39;).find(&#39;.lightbox-item&#39;);
        var $prev = $wps.filter(&#39;.prev&#39;);
        var $curr = $wps.filter(&#39;.current&#39;);
        var $next = $wps.filter(&#39;.next&#39;);
        if (target === &#39;.prev&#39;) {
            idx--;
            $prev.attr(&#39;class&#39;, &#39;lightbox-item current&#39;);
            $curr.attr(&#39;class&#39;, &#39;lightbox-item next&#39;);
            $next.attr(&#39;class&#39;, &#39;lightbox-item prev&#39;);
            prefetch(&#39;.prev&#39;, idx - 1);
        } else if (target === &#39;.next&#39;) {
            idx++;
            $next.attr(&#39;class&#39;, &#39;lightbox-item current&#39;);
            $curr.attr(&#39;class&#39;, &#39;lightbox-item prev&#39;);
            $prev.attr(&#39;class&#39;, &#39;lightbox-item next&#39;);
            prefetch(&#39;.next&#39;, idx + 1);
        }
        $(.container).css(&#39;transform&#39;, &#39;none&#39;);
        $(.container).css(&#39;-webkit-transform&#39;, &#39;none&#39;);
    }
});

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(&#39;src&#39;, 
        &#39;data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==&#39;);
    // 载入图片到临时变量
    var tmp = new Image();
    tmp.onload = function(){
        // 资源载入后,将资源显示到目标的img
        $img.src = src;
    };
    tmp.src = src;
}

  设置背景图与设置src属性一样,均可以使用该策略。浏览器会复用那个资源。

  图片到底提示

  在第一张图片右划和最后一张图片左划时,应当给出提示。 可以做一张带有提示信息的Placeholder:

$lightbox.attr(&#39;style&#39;, &#39;top:0;left:0;right:0;bottom:0;&#39;);
$lightbox.append($(&#39;<p class="alert-nomore">&#39;).html(&#39;没有更多了..&#39;));

  然后让文字居中:

.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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn