? ? ? ?今天學(xué)習(xí)的內(nèi)容,他的主要原理是等著圖片滾動,滾動到一半時(shí)再把它扯回來,實(shí)際也就是說是一個(gè)障眼法。?具體由oul.style.left=-oul.offsetWidth/2;(注意負(fù)值)實(shí)現(xiàn)了扯回來的效果。offsetLeft 獲取的是相對于父對象的左邊距。其中預(yù)先使用?clearInterval(timer);的目的是防止重復(fù)點(diǎn)擊速度加快。
代碼很多都不是用offsetleft寫的,網(wǎng)上找了一下找到了,可以更容易的理解定時(shí)器。
主要思路是
1.計(jì)算圖片列表ul的寬度
2.開啟定時(shí)器,使其向左邊距不斷增大,造成向左運(yùn)動的效果
3.圖片列表復(fù)制一份,向左移動時(shí),當(dāng)左邊距大于一份的寬度時(shí),把它的左邊距拉回到0。向右移動時(shí),當(dāng)左邊距大于0時(shí),把它的左邊距拉到整個(gè)兩份圖片列表一半的寬度(即一份的寬度)。(拉的瞬間很快,用戶察覺不到,造成一種無縫滾動的假象)
4.offsetLeft值的正負(fù)決定往哪邊移動
5.放到圖片上停止這個(gè)定時(shí)器,移開再開啟

window.onload=function(){
?varodiv=document.getElementById('div');
?varoul=odiv.getElementsByTagName('ul')[0];
?varoli=oul.getElementsByTagName('oul');
?varbtn=document.getElementsByTagName('btn');
?varispeed=-1;
?vartimer=null;
?oul.innerHTML+=oul.innerHTML; //圖片列表復(fù)制一份
?oul.style.width=oli[0].offsetWidth*oli.length+'px'; //不算出ul的寬度的話,運(yùn)動過程中后面的會先出現(xiàn)再加載圖片,有一種不流暢感,切圖片過多會分行,由外面的div決定寬度
?timer=setInterval(function(){
??oul.style.left=oul.offsetLeft+ispeed+'px';? //offsetLeft輸出的是數(shù)字不帶單位,右邊也用oul.style.left輸出的是字符串,而不是數(shù)值,而且它取得是行間樣式,無用
??if(oul.offsetLeft<-oul.offsetWidth/2){ //判斷時(shí)也可以用.style.left或.style.width?(不確定)
???oul.style.left=0;
??}
??elseif(oul.offsetLeft>0){
???oul.style.left=-oul.offsetWidth/2;
??}
?),30};
?btn[0].onmouseover=function(){
??ispeed=-1;
?};
?btn[1].onmouseover=function(){
??ispeed=1;
?};
?oul.onmouseover=function(){
??clearInterval(timer);
?};
?oul.onmouseout=function(){
??timer=setInterval(function(){
???oul.style.left=oul.offsetLeft+ispeed+'px';
???if(oul.offsetLeft<-oul.offsetWidth/2){
????oul.style.left=0;
???}
???elseif(oul.offsetLeft>0){
????oul.style.left=-oul.offsetWidth/2;
???}
??),30}; //如果把速度變大,而定時(shí)器的時(shí)間也變大是否可以達(dá)到相同效果呢?答案是不能。會變成一卡一卡
?};
};