May 2, 2019

前端輪播套件:Owl Carousel

支援拖曳、滾動、跨瀏覽器、hash、分頁事件


文 / 西打藍 Siddharam

前言


Owl Carousel 的 DocGitHub

最近接了室內設計公司的官網外包案,需要做到點擊後,向右換頁的輪播效果,有類似翻書的感覺,並且沒有切換 URL。而公司的某個專案正好有用到 Owl Carousel 這個套件,用起來也沒什麼 bug,就繼續採用了。

開始


首先須下載 Owl Carousel 的套件,另外要記得引入 jQuery,目前是用 CDN 方式引入。請去除空白:

< script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">

接著,我們就來寫看我所需要的效果


// html
// 因為 markdown 關係,每個標籤都有空格,如需使用,記得移除
// 當點擊 back,會跳轉到該 hash 
< div class="owl-carousel" > < div data-hash="slide1" style="background:red;"> Your Content 第一頁 < button class="next" >click< /button> < /div> < div data-hash="slide2" style="background:yellow;"> Your Content 第二頁 < button class="next">click< /button> < a href="index.html#slide1">back< /a> < /div> < div>



// javascript
$(document).ready(function(){ $(".owl-carousel").owlCarousel({ items: 1, // 每頁有多少筆 loop: false, center: true, mouseDrag: false, // 滑鼠拖曳 touchDrag: false, // 觸控拖曳 pullDrag: false, URLhashListener: true, //紀錄 a 標籤,如上面的 data-hash="slide1" startPosition: 'URLHash', // 可為 string / number dotsContainer: '.custom-dots', // nav bar 的名稱 responsiveRefreshRate: 0, // 每多久計算一次 client 瀏覽器寬度 responsive: { // 不同 width 下的調整 0: { margin: 0, autoWidth: false }, 992: { autoWidth: false } } }); // next.owl.carousel 事件,可以跳轉至下一張 slide $('.next').click(function () { $(".owl-carousel").trigger('next.owl.carousel') }) });


如果 mobile 變化較大,可以另外寫一組 config。接下來若有新的樣式需求,會持續補充。




閱讀量




聯絡與合作


有文字採訪、網站開發,或是諮詢需求,皆可至個人網站參考作品,並聯繫 IG

或是想分享心情、聊聊天、交朋友,可以來秘密通道找我唷。

Email: frank@siddharam.com

訂閱: