JavaScript一種直譯式腳本語言,是一種動態類型、弱類型、基於原型的語言,內置支持類型。它的解釋器被稱為JavaScript引擎,為瀏覽器的一部分,廣泛用於客戶端的腳本語言,最早是在html(標準通用標記語言下的一個應用)網頁上使用,用來給HTML網頁增加動態功能。
背景:
想要實現圖片持續滾動,既然使用js,就千萬不要加css動畫、過渡等相關樣式,如果想要滾動的平滑一下,可以一像素一像素的感動,則很平滑,如果加了過渡動畫,當圖片重置為0時,會有往回倒的動畫效果,跟預期不符。
原理:
圖片滾動原理同圖片輪播原理,同樣也適用於文字滾動等一系列滾動,通過複製最後一張圖片或最後一堆文字插入第一行,或複製第一張圖片或一堆文字插入在結尾,來實現無縫拼接,前提:1、必須是沒有設置過渡動畫的,2、重置為0的時候與當前已經滾動到的高度對於圖片的位置而言肉眼看上去沒變化。
實現:
html主要包含三塊:
1、最外層盒子,用來展示滾動圖的區域,overflow:hidden;
2、滾動的盒子,主要改變該盒子的定位值,來實現滾動,裡面包含所有要滾動的圖片或文字
3、包含圖片或文字的盒子。
代碼:
classRoll{
constructor(opts){
this.elem=opts.elem;//圖片包含滾動長度的元素的
this.elemBox=opts.elemBox;//圖片展示區域元素,為了獲取展示區域的高度
this.direction=opts.direction;
this.time=opts.time;
this.init();
this.roll=this.roll.bind(this)
this.startRoll=this.startRoll.bind(this)
this.stopRoll=this.stopRoll.bind(this)
}
init(){
this.elemHeight=this.elem.offsetHeight;
this.elemHtml=this.elem.innerHTML;
this.elem.innerHTML=this.elem.innerHTML+this.elemHtml+this.elemHtml;
this.speed;
//如果向上滾或者向左滾動每次減1,向下滾或者向右滾動每次加1
if(this.direction===&39;||this.direction===&39;){
this.speed=-1;
}else{
this.speed=1;
}
}
roll(){
switch(this.direction){
case&34;:
//如果滾動的盒子的top值超出元素的高度,則值為0
if(Math.abs(this.elemBox.offsetTop)>=this.elemHeight){
this.elemBox.style.top=0;
}else{
this.elemBox.style.top=this.elemBox.offsetTop+this.speed+&39;;
}
break;
case&34;:
//如果滾動的盒子的bottom值超出元素的高度,則值為0
if(Math.abs(this.elemBox.offsetBottom)>=this.elemHeight){
this.elemBox.style.bottom=0;
}else{
this.elemBox.style.bottom=this.elemBox.offsetBottom+this.speed+&39;;
}
break;
case&34;:
//如果滾動的盒子的left超出元素的高度,則置為0
if(Math.abs(this.elemBox.offsetLeft)>=this.elemHeight){
this.elemBox.style.left=0;
}else{
this.elemBox.style.left=this.elemBox.offsetLeft+this.speed+&39;;
}
break;
case&34;:
//如果滾動的盒子的right超出元素的高度,則置為0
if(Math.abs(this.elemBox.offsetRight)>=this.elemHeight){
this.elemBox.style.right=0;
}else{
this.elemBox.style.right=this.elemBox.offsetRight+this.speed+&39;;
}
break;
default:
//默認向上滾動,如果滾動的盒子的top超出元素的高度,則置為0
if(Math.abs(this.elemBox.offsetTop)>=this.elemHeight){
this.elemBox.style.top=0;
}else{
this.elemBox.style.top=this.elemBox.offsetTop+speed+&39;;
}
}
}
stopRoll(){
clearInterval(this.scrollTimer)
}
startRoll(){
this.scrollTimer=setInterval(this.roll,this.time)
}
}
在1995年時,由Netscape公司的BrendanEich,在網景導航者瀏覽器上首次設計實現而成。因為Netscape與Sun合作,Netscape管理層希望它外觀看起來像java,因此取名為JavaScript。但實際上它的語法風格與Self及Scheme較為接近。js實現單張或多張圖片持續無縫滾動。
開課吧Web前端教程