swiper.vue 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. <template>
  2. <div class="nut-swiper"
  3. :class="[direction,{'dragging':dragging}]"
  4. @touchstart="_onTouchStart($event)"
  5. @mousedown="_onTouchStart($event)" >
  6. <div class="nut-swiper-wrap"
  7. :style="{
  8. 'transform':'translate3d('+translateX+'px,'+translateY+'px,0)',
  9. 'transition-duration':transitionDuration+'ms',
  10. '-webkit-transform':'translate3d('+translateX+'px,'+translateY+'px,0)',
  11. '-webkit-transition-duration':transitionDuration+'ms',
  12. 'transition-timing-function':'ease'
  13. }"
  14. @transitionend="_onTransitionEnd">
  15. <slot></slot>
  16. </div>
  17. <div class="nut-swiper-pagination" v-show="paginationVisible">
  18. <span class="swiper-pagination-bullet" :class="{'active':index+1 ===currentPage}" v-for="(slide,index) in slideEls" @click="paginationClickable && setPage(index+1)" :key="index">
  19. </span>
  20. </div>
  21. </div>
  22. </template>
  23. <script>
  24. const VERTICAL = 'vertical';
  25. const HORIZONTAL = 'horizontal';
  26. export default {
  27. name:'nut-swiper',
  28. props: {
  29. direction:{
  30. type:String,
  31. default:VERTICAL,
  32. validator:(value) => [VERTICAL,HORIZONTAL].indexOf(value) >-1
  33. },
  34. paginationVisible:{
  35. type:Boolean,
  36. default:false
  37. },
  38. paginationClickable:{
  39. type:Boolean,
  40. default:false
  41. },
  42. loop:{
  43. type:Boolean,
  44. default:false
  45. },
  46. speed:{
  47. type:Number,
  48. default:500
  49. },
  50. performanceMode:{//性能标识 默认是false, 主要是正对拖拽过程中的移动
  51. type:Boolean,
  52. default:false
  53. },
  54. autoPlay:{
  55. type:Number,
  56. default:0
  57. },
  58. lazyLoad:{//图片lazy
  59. type:Boolean,
  60. default:false
  61. },
  62. lazyLoadingUrl:{
  63. type:String,
  64. },
  65. lazyLoaderrorUrl:{
  66. type:String,
  67. },
  68. freeMode:{
  69. type:Boolean,
  70. default:false
  71. },
  72. initPage:{
  73. type:Number,
  74. default:1,
  75. },
  76. type:{
  77. type:String,
  78. default:'single',
  79. }
  80. },
  81. data() {
  82. return {
  83. dragging:false,
  84. currentPage:this.initPage,
  85. lastPage:1,
  86. translateX:0,
  87. translateY:0,
  88. startTranslate:0,
  89. transitioning:false,//动画执行时间
  90. slideEls:[],
  91. translateOffset:0,//当前偏移初始位置的距离
  92. transitionDuration:0,
  93. startPos:null,
  94. delta:0,//拖动的距离间隔
  95. startTime:'',
  96. isLoop:this.loop,
  97. timer:null,// 自动播放计数器
  98. stopAutoPlay:false,//停止自动播放
  99. swiperWrap:null,// swiperWrap dom
  100. oneSlideTranslate:0,//一个slide 的距离用于判断,手指停在第几个silde上了
  101. };
  102. },
  103. methods: {
  104. next(sPage){
  105. if(sPage && this.type==='multiple'){
  106. if(sPage < this.slideEls.length){
  107. this.setPage(sPage+1);
  108. return;
  109. }else{
  110. this.setPage(this.slideEls.length);
  111. return;
  112. }
  113. }
  114. let page = this.currentPage;
  115. if(page <this.slideEls.length || this.isLoop){
  116. this.setPage(page + 1,false,'next');
  117. }else{
  118. this._revert();
  119. }
  120. },
  121. prev(sPage){
  122. if(sPage && this.type==='multiple'){
  123. if(sPage > 0){
  124. this.setPage(sPage+1);
  125. return;
  126. }else{
  127. this.setPage(0);
  128. return;
  129. }
  130. }
  131. let page = this.currentPage;
  132. if(page > 1 || this.isLoop){
  133. this.setPage(page - 1,false,'prev');
  134. }else{
  135. this._revert();
  136. }
  137. },
  138. setPage(page,noAnimation,cType){
  139. if(page === 0){
  140. this.currentPage = this.slideEls.length;
  141. }else if(page === this.slideEls.length + 1){
  142. this.currentPage = 1;
  143. }else{
  144. this.currentPage = page;
  145. }
  146. if(this.isLoop){
  147. this._setTranslate(this._getTranslateOfPage(page));
  148. if(noAnimation) {
  149. //添加select cls
  150. let selectedSlide = this.$el.querySelector('.nut-swiper-silde-selected');
  151. selectedSlide && selectedSlide.classList.remove('nut-swiper-silde-selected');
  152. this.slideEls[this.currentPage-1].classList.add('nut-swiper-silde-selected');
  153. this.lastPage = this.currentPage;
  154. return;
  155. }
  156. this._onTransitionStart(cType);
  157. }else{
  158. this._setTranslate(this._getTranslateOfPage(page));
  159. if(noAnimation) {
  160. //添加select cls
  161. let selectedSlide = this.$el.querySelector('.nut-swiper-silde-selected');
  162. selectedSlide && selectedSlide.classList.remove('nut-swiper-silde-selected');
  163. this.slideEls[this.currentPage-1].classList.add('nut-swiper-silde-selected');
  164. this.lastPage = this.currentPage;
  165. return;
  166. };
  167. this._onTransitionStart(cType);
  168. }
  169. },
  170. isHorizontal(){
  171. return this.direction === HORIZONTAL;
  172. },
  173. isVertical(){
  174. return this.direction === VERTICAL;
  175. },
  176. updateSlidesBindEvent(pageSize){
  177. this.$nextTick(()=>{
  178. if(pageSize!=undefined) this.currentPage = pageSize;
  179. this.swiperWrap = this.$el.querySelector('.nut-swiper-wrap');
  180. this.slideEls = [].map.call(this.swiperWrap.children,el=>el);
  181. if(this.slideEls.length === 0) return;
  182. this._getSlideDistance((this.slideEls)[0]);
  183. if(this.autoPlay != 0 ){
  184. this.isLoop = true;
  185. this._createAutoPlay();
  186. }
  187. if(this.isLoop){
  188. this._createLoop();
  189. this.setPage(this.currentPage,true);
  190. }else{
  191. this.setPage(this.currentPage,true);
  192. }
  193. this.lazyLoad && this._imgLazyLoad();//第一次进来时候
  194. });
  195. },
  196. _getSlideDistance(el){
  197. //let propName = this.isHorizontal() ? 'offsetWidth' : 'offsetHeight';
  198. let styleArr = getComputedStyle(el);
  199. let marginTop = styleArr['marginTop'].replace('px','') - 0;
  200. let marginBottom = styleArr['marginBottom'].replace('px','') - 0;
  201. let marginRight = styleArr['marginRight'].replace('px','') - 0;
  202. let marginLeft = styleArr['marginLeft'].replace('px','') - 0;
  203. if(this.isHorizontal()){
  204. this.oneSlideTranslate = marginLeft + marginRight + el['offsetWidth'];
  205. }else{
  206. this.oneSlideTranslate = marginBottom + marginTop + el['offsetHeight'];
  207. }
  208. },
  209. _onTouchStart(e){
  210. this.swiperWrap.addEventListener('touchmove',this._onTouchMove,false);
  211. this.swiperWrap.addEventListener('touchend',this._onTouchEnd,false);
  212. this.swiperWrap.addEventListener('mousemove',this._onTouchMove,false);
  213. this.swiperWrap.addEventListener('mouseup',this._onTouchEnd,false);
  214. this.startPos = this._getTouchPos(e);
  215. this.delta = 0;
  216. if(!this.freeMode){
  217. this.startTranslate = this._getTranslateOfPage(this.currentPage);
  218. if(this.isLoop){
  219. this._setTranslate(this.startTranslate);
  220. }
  221. }
  222. this.startTime = new Date().getTime();
  223. this.dragging = true;
  224. this.transitionDuration = 0;
  225. this.stopAutoPlay = true;
  226. },
  227. _onTouchMove(e){
  228. if(!this.dragging){
  229. return;
  230. }
  231. this.delta = this._getTouchPos(e) - this.startPos;
  232. if((this.isHorizontal() && Math.abs(this.delta) > 0) || this.isVertical()){
  233. //e.preventDefault();
  234. }
  235. let isQuickAction = new Date().getTime() -this.startTime < 200;
  236. if(!this.performanceMode && !isQuickAction){
  237. this.lazyLoad && this._imgLazyLoad();
  238. this._setTranslate(this.startTranslate + this.delta);
  239. this.$emit('slideMove',this._getTranslate(),this.$el);
  240. }
  241. },
  242. _onTouchEnd(e){
  243. if(!this.dragging) return;
  244. if(this.freeMode){
  245. let translate = this._getTranslate();
  246. let maxTransalte = this._getTranslateFreeLastPage();
  247. if(translate > 0 || maxTransalte > 0){
  248. this._setTranslate(0);
  249. this._onTransitionStart();
  250. }else if(translate < maxTransalte){
  251. this._setTranslate(maxTransalte);
  252. this._onTransitionStart();
  253. }else{
  254. this.startTranslate = translate;
  255. }
  256. return;
  257. }else{
  258. this.dragging = false;
  259. this.transitionDuration = this.speed;
  260. let isQuickAction = new Date().getTime() -this.startTime < 1000;
  261. let currPage = 0;
  262. if(this.type === 'multiple'){
  263. let currTranslate = this._getTranslate();
  264. currPage = currTranslate/this.oneSlideTranslate;
  265. if(currPage > 0){
  266. currPage = 0;
  267. }
  268. }
  269. currPage = Math.round(Math.abs(currPage));
  270. if(this.delta < -this.oneSlideTranslate/2 || (isQuickAction && this.delta < -15)){
  271. this.next(currPage);
  272. }else if(this.delta > this.oneSlideTranslate/2 || (isQuickAction && this.delta > 15)){
  273. this.prev(currPage);
  274. }else{
  275. this._revert();
  276. }
  277. }
  278. this.swiperWrap.removeEventListener('touchmove',this._onTouchMove,false);
  279. this.swiperWrap.removeEventListener('touchend',this._onTouchEnd,false);
  280. this.swiperWrap.removeEventListener('mousemove',this._onTouchMove,false);
  281. this.swiperWrap.removeEventListener('mouseup',this._onTouchEnd,false);
  282. },
  283. _revert(){
  284. this.setPage(this.currentPage);
  285. },
  286. _getTouchPos(e){
  287. let key = this.isHorizontal() ? 'pageX' : 'pageY';
  288. return e.changedTouches ? e.changedTouches[0][key] : e[key];
  289. },
  290. _onTransitionStart(cType){
  291. this.transitioning = true;
  292. this.transitionDuration = this.speed;
  293. this.lazyLoad && this._imgLazyLoad(1);//1 表示是动画切换到下一屏幕
  294. if(this._isPageChanged()){
  295. this.$emit('slideChangeStart',this.currentPage,this.$el,cType);
  296. }else{
  297. this.$emit('slideRevertStart',this.currentPage,this.$el,cType);
  298. }
  299. },
  300. _onTransitionEnd(){
  301. this.transitioning = false;
  302. this.transitionDuration = 0;
  303. this.delta = 0;
  304. if(this._isPageChanged()){
  305. this.$emit('slideChangeEnd',this.currentPage,this.$el);
  306. }else{
  307. this.$emit('slideRevertEnd',this.currentPage,this.$el);
  308. }
  309. this.lastPage = this.currentPage;
  310. //添加select cls
  311. let selectedSlide = this.$el.querySelector('.nut-swiper-silde-selected');
  312. selectedSlide && selectedSlide.classList.remove('nut-swiper-silde-selected');
  313. this.slideEls[this.currentPage-1].classList.add('nut-swiper-silde-selected');
  314. if(this.isLoop){
  315. this._setTranslate(this._getTranslateOfPage(this.currentPage));
  316. }
  317. this.stopAutoPlay = false;
  318. },
  319. _isPageChanged(){
  320. return this.lastPage !== this.currentPage;
  321. },
  322. _setTranslate(value){
  323. let translateName = this.isHorizontal() ? 'translateX' : 'translateY';
  324. this[translateName] = value;
  325. },
  326. _getTranslate(){
  327. let translateName = this.isHorizontal() ? 'translateX' : 'translateY';
  328. return this[translateName];
  329. },
  330. _getTranslateOfPage(page){
  331. if(page === 0) return 0;
  332. let propName = this.isHorizontal() ? 'offsetWidth' : 'offsetHeight';
  333. let _this = this;
  334. return -[].reduce.call(this.slideEls,function(total,el,i){
  335. return i > page - 2 ? total : total + _this.oneSlideTranslate;
  336. },0) + this.translateOffset;
  337. },
  338. _getTranslateFreeLastPage(){
  339. let slideLength = this.slideEls.length;
  340. let propName = this.isHorizontal() ? 'offsetWidth' : 'offsetHeight';
  341. return this.swiperWrap[propName] - [].reduce.call(this.slideEls,function(total,el,i){
  342. let computedStyle = window.getComputedStyle(el,null);
  343. let marginRight = computedStyle['marginRight'].replace('px','') * 1;
  344. let marginLeft = computedStyle['marginLeft'].replace('px','') * 1;
  345. if(i > slideLength - 2){
  346. marginLeft = marginRight = 0;
  347. }
  348. return total + el[propName] + marginRight + marginLeft;
  349. },0);
  350. },
  351. _createLoop(){
  352. let propName = this.isHorizontal() ? 'offsetWidth' : 'offsetHeight';
  353. let swiperWrapEl = this.$el.querySelector('.nut-swiper-wrap');
  354. let duplicateFirstChild = swiperWrapEl.firstElementChild.cloneNode(true);
  355. let duplicateLastChild = swiperWrapEl.lastElementChild.cloneNode(true);
  356. swiperWrapEl.insertBefore(duplicateLastChild, swiperWrapEl.firstElementChild);
  357. swiperWrapEl.appendChild(duplicateFirstChild);
  358. this.translateOffset = - duplicateLastChild[propName];
  359. },
  360. _createAutoPlay(){
  361. clearInterval(this.timer);
  362. this.timer = setInterval(()=>{
  363. if(!this.stopAutoPlay){//如果停止播放,就不执行next
  364. this.next();
  365. }
  366. },this.autoPlay);
  367. },
  368. _requestAniFrame(){
  369. return window.requestAnimationFrame ||
  370. window.webkitRequestAnimationFrame ||
  371. window.mozRequestAnimationFrame ||
  372. function( callback ){
  373. window.setTimeout(callback, 1000 / 60);
  374. };
  375. },
  376. _imgLazyLoad(type){
  377. let requestAniFrame = this._requestAniFrame();
  378. let imgLazyLoadEl;
  379. requestAniFrame(()=>{
  380. imgLazyLoadEl = this.swiperWrap.querySelectorAll('.nut-swiper-lazyload');
  381. if(type == 1){
  382. imgLazyLoadEl = this.slideEls[this.currentPage-1].querySelectorAll('.nut-swiper-lazyload');
  383. }
  384. imgLazyLoadEl.forEach((item,index)=>{
  385. if(!this._checkInView(item) && type != 1) return;
  386. let src = item.getAttribute('data-src');
  387. item.src = this.lazyLoadingUrl;
  388. let img = new Image();
  389. img.src = src;
  390. img.onload = function(){
  391. item.src = src;
  392. item.classList.remove('nut-swiper-lazyload');
  393. }
  394. img.onerror= function(){
  395. item.src = this.lazyLoaderrorUrl;
  396. item.classList.remove('nut-swiper-lazyload');
  397. }
  398. });
  399. });
  400. },
  401. _checkInView(imgItem){
  402. let imgRect = imgItem.getBoundingClientRect();
  403. let swiperRect = this.$el.getBoundingClientRect();
  404. let imgTop = imgRect.top;
  405. let imgLeft = imgRect.left;
  406. let swiperWidth = this.$el.clientWidth;
  407. let swiperHeight = this.$el.clientHeight;
  408. let swiperTop = swiperRect.top;
  409. let swiperLeft = swiperRect.left;
  410. let isInView = true;
  411. if(imgTop > swiperTop + swiperHeight || imgLeft > swiperLeft + swiperWidth){
  412. isInView = false;
  413. }
  414. return isInView;
  415. },
  416. },
  417. created:function(){
  418. },
  419. mounted:function(){
  420. this._onTouchMove = this._onTouchMove.bind(this);
  421. this._onTouchEnd = this._onTouchEnd.bind(this);
  422. this.updateSlidesBindEvent();
  423. }
  424. }
  425. </script>
  426. <style lang="scss">
  427. .nut-swiper {
  428. position: relative;
  429. overflow: hidden;
  430. height: 200px;
  431. .nut-swiper-wrap {
  432. display: flex;
  433. display: -webkit-flex;
  434. width: 100%;
  435. height: 100%;
  436. transition: all 0ms ease;
  437. -webkit-transition: all 0ms ease;
  438. }
  439. .nut-swiper-silde {
  440. overflow: hidden;
  441. flex-shrink: 0;
  442. -webkit-flex-shrink: 0;
  443. width: 100%;
  444. height: 100%;
  445. cursor: default;
  446. }
  447. &.horizontal .nut-swiper-wrap {
  448. flex-direction: row;
  449. -webkit-flex-direction:row;
  450. }
  451. &.vertical .nut-swiper-wrap {
  452. flex-direction: column;
  453. -webkit-flex-direction: column;
  454. }
  455. .nut-swiper-pagination {
  456. position: absolute;
  457. .swiper-pagination-bullet {
  458. width: 8px;
  459. height: 8px;
  460. border-radius: 50%;
  461. background-color: #000000;
  462. opacity: .2;
  463. transition: all .5s ease;
  464. -webkit-transform: all .5s ease;
  465. }
  466. .swiper-pagination-bullet.active {
  467. background: #007aff;
  468. opacity: 1;
  469. }
  470. }
  471. &.vertical .nut-swiper-pagination {
  472. right: 10px;
  473. top: 50%;
  474. transform: translate3d(0, -50%, 0);
  475. -webkit-transform: translate3d(0,-50%,0);
  476. .swiper-pagination-bullet {
  477. display: block;
  478. margin: 6px 0;
  479. }
  480. }
  481. &.horizontal .nut-swiper-pagination {
  482. bottom: 10px;
  483. width: 100%;
  484. text-align: center;
  485. .swiper-pagination-bullet {
  486. display: inline-block;
  487. margin: 0 3px;
  488. }
  489. }
  490. }
  491. </style>