縦スクロールアニメーションで記事タイトル表示
コードをオブジェクト指向で記載したサンプルを掲載します。
サンプルプログラム
https://choppydays.com/static/newsticker/newsticker_class.php
HTML
<div class="news_area"> <div id="news_ticker" class="news_ticker"> <div class="news_ticker_inner"> <div class="list"> <article class="item"> <p class="time">2021/4/1</p> <h3 class="title"> タイトル1 </h3> </article> <article class="item"> <p class="time">2021/5/1</p> <h3 class="title"> タイトル2 </h3> </article> <article class="item"> <p class="time">2021/6/1</p> <h3 class="title"> タイトル3 </h3> </article> </div> </div> </div> </div>
CSS
.time, .title { display: inline; } .news_ticker .news_ticker_inner { height: 30px; overflow: hidden; width: 400px; border: 1px solid #aaa; } .news_ticker .posts { padding: 0 0 0 38px; position: relative; } .news_area { border: 1px solid #333; padding: 10px; }
javascript(jQuery)
$(document).ready(function(){ var newsTicker = new NewsTicker('#news_ticker','.list', '.item'); newsTicker.autoPlay(); }); class NewsTicker{ constructor(newsticker_elm, list_elm, item_elm){ this.ticker = $(newsticker_elm); this.list = this.ticker.find(list_elm); this.item = this.ticker.find(item_elm); this.clone = this.item.eq(0).clone().addClass('is-clone'); this.timer; this.current = 1; this.num_of_item = this.item.length; this.distance = parseInt(this.item.css('height'),10); this.list.append(this.clone); self = this; this.ticker.on({ 'mouseenter': function(){ clearTimeout(self.timer); }, 'mouseleave': function(){ self.autoPlay(); } }); } rotate(){ this.list.stop().animate({ top: self.distance * self.current * -1, }, 1500, function() { if (self.current >= self.num_of_item) { self.current = 1; self.list.css({top: 0}); } else { self.current++; } }); } autoPlay() { this.timer = setInterval(function() { self.rotate(); }, 3500); } }