腾挪手机APP滑动手指切换图片特效
移动手机APP滑动手指切换图片特效
这是一款效果非常炫酷的移动手机APP滑动手指切换图片特效。该APP特效在移动手机中用户可以通过手指的左右滑动来切换图片,在桌面设备中通过鼠标也可达到同样的效果。
使用方法
HTML结构
这个移动手机APP切换图片特效的HTML结构采用嵌套<div>
的HTML结构,每一张图片卡片都包裹在div.demo__card
中,里面放置了图片,描述信息和一些额外的图层。
1
2
3
4
5
6
7
8
9
10
11
12
|
< div class = "demo__card" >
< div class = "demo__card__top brown" >
< div class = "demo__card__img" ></ div >
< p class = "demo__card__name" >Hungry cat</ p >
</ div >
< div class = "demo__card__btm" >
< p class = "demo__card__we" >Whatever</ p >
</ div >
< div class = "demo__card__choice m--reject" ></ div >
< div class = "demo__card__choice m--like" ></ div >
< div class = "demo__card__drag" ></ div >
</ div >
|
m--reject
是向左移动图片时的图层,m--like
是向右移动图片时的图层,demo__card__drag
是拖动层。
JavaScript
在jQuery代码中,pullChange()
函数用于设置向左和向右两个滑动层的旋转角度和透明度。release()
函数用于判断用户是向左还是向右滑动手指,并为这些动作在DOM元素上添加相应的class。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
function pullChange() {
animating = true ;
deg = pullDeltaX / 10;
$card.css( 'transform' , 'translateX(' + pullDeltaX + 'px) rotate(' + deg + 'deg)' );
var opacity = pullDeltaX / 100;
var rejectOpacity = opacity >= 0 ? 0 : Math.abs(opacity);
var likeOpacity = opacity <= 0 ? 0 : opacity;
$cardReject.css( 'opacity' , rejectOpacity);
$cardLike.css( 'opacity' , likeOpacity);
} ; function release() {
if (pullDeltaX >= decisionVal) {
$card.addClass( 'to-right' );
} else if (pullDeltaX <= -decisionVal) {
$card.addClass( 'to-left' );
}
if (Math.abs(pullDeltaX) >= decisionVal) {
$card.addClass( 'inactive' );
setTimeout( function () {
$card.addClass( 'below' ).removeClass( 'inactive to-left to-right' );
cardsCounter++;
if (cardsCounter === numOfCards) {
cardsCounter = 0;
$( '.demo__card' ).removeClass( 'below' );
}
}, 300);
}
if (Math.abs(pullDeltaX) < decisionVal) {
$card.addClass( 'reset' );
}
setTimeout( function () {
$card.attr( 'style' , '' ).removeClass( 'reset' ).find( '.demo__card__choice' ).attr( 'style' , '' );
pullDeltaX = 0;
animating = false ;
}, 300);
}; |
最后监听mousedown
和touchstart
事件,并对非.inactive
的卡片元素执行卡片切换操作。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
$(document).on( 'mousedown touchstart' , '.demo__card:not(.inactive)' , function (e) {
if (animating)
return ;
$card = $( this );
$cardReject = $( '.demo__card__choice.m--reject' , $card);
$cardLike = $( '.demo__card__choice.m--like' , $card);
var startX = e.pageX || e.originalEvent.touches[0].pageX;
$(document).on( 'mousemove touchmove' , function (e) {
var x = e.pageX || e.originalEvent.touches[0].pageX;
pullDeltaX = x - startX;
if (!pullDeltaX)
return ;
pullChange();
});
$(document).on( 'mouseup touchend' , function () {
$(document).off( 'mousemove touchmove mouseup touchend' );
if (!pullDeltaX)
return ;
release();
});
}); |