Tab選項(xiàng)卡切換我遇到了三個(gè)問(wèn)題,求大神解答,謝謝
function $(id){
? ?return typeof id === 'string'?document.getElementById(id):id;
}
window.onload = function(){
? ?var lis = $('notice-tit').getElementsByTagName('li');
? ?var divs = $('notice-con').getElementsByTagName('div');
? ?var index = 0;
? ?var timer = null;
? ?for(var i=0;i<lis.length;i++){
? ? ? ?lis[i].id = i;
? ? ? ?lis[i].onmouseenter = function(){
? ? ? ? ? ?clearInterval(timer);
? ? ? ? ? ?changeOption(this.id);
? ? ? ?};
? ? ? ?lis[i].onmouseleave = function(){
? ? ? ? ? ?timer = setInterval(autoPlay,2000);
? ? ? ?}
? ?}
? ?if(timer){
? ? ? ?clearInterval(timer);
? ? ? ?timer=null;
? ?} //clearInterval(timer); ???有啥區(qū)別?為啥刪了if(timer){}也沒(méi)事??
? ?timer = setInterval(autoPlay,2000);
? ?function autoPlay() {
? ? ? ?index++;
? ? ? ?if (index >= lis.length) {
? ? ? ? ? ?index = 0;
? ? ? ?}
? ? ? ?changeOption(index);
? ?}
? ?function changeOption(currentIndex){
? ? ? ?for(var j=0;j<lis.length;j++){
? ? ? ? ? ?lis[j].className = '';
? ? ? ? ? ?divs[j].style.display = 'none';
? ? ? ?}
? ? ? ?lis[currentIndex].className = 'select';
? ? ? ?divs[currentIndex].style.display = 'block';
? ? ? ?index = currentIndex;
? ?}
};
一: ?onmouseleave事件中,如果啟動(dòng)定時(shí)器不寫(xiě)timer= ?的時(shí)候,鼠標(biāo)離開(kāi)它會(huì)自動(dòng)亂切換,亂跳;具體代碼:lis[i].onmouseleave = function(){
? ? ? ? ? ?setInterval(autoPlay,2000);
? ? ? ?}?
????????為什么一定要寫(xiě)成 timer = setInterval(autoPlay,2000);?
二、鼠標(biāo)放在內(nèi)容標(biāo)簽里,標(biāo)題標(biāo)簽還是自動(dòng)切換,對(duì)用戶(hù)體驗(yàn)不好,用戶(hù)肯定想把鼠標(biāo)放在內(nèi)容上瀏覽內(nèi)容,標(biāo)題標(biāo)簽不切換,怎么解決?
第三點(diǎn) ?if(timer){
? ? ? ?clearInterval(timer);
? ? ? ?timer=null;
? ?} ?為什么不換成 clearInterval(timer); ??
? ?我試了下為什么timer=null;不寫(xiě)也沒(méi)影響?
? ?甚至這兩種方法都不寫(xiě)也沒(méi)影響啊,我試了下,并沒(méi)有出現(xiàn)老師說(shuō)的快速切換多個(gè)動(dòng)畫(huà)BUG,很正常的切換啊,怎么回事?
2017-08-15
1;因?yàn)槟銢](méi)有指定timer變量去承載這個(gè)方法,方法就找不到執(zhí)行的規(guī)律
2:可以直接獲取內(nèi)容,并遍歷執(zhí)行切換函數(shù)
3:給clear=null;是為了讓程序有更好的可讀性,并從新賦值給clear,避免不必要的bug