今天,主管要我處理一個網站的相容性問題。一般來說,相容性問題多半是「相容其他瀏覽器、唯獨 IE 不相容」,而這個案例有點特殊:它只相容 IE,反而在其他瀏覽器上跑不動。初步觀察後我發現,問題出在 JavaScript,跟 div 和 CSS 沒有什麼關係。
這是原來的程式碼:
<SCRIPT language=JavaScript>
marqueesHeight=550;
stopscroll=false;with(flash){
style.width=235;
style.height=marqueesHeight;
style.overflowX=”visible”;
style.overflowY=”hidden”;
noWrap=true;
onmouseover=new Function(“stopscroll=true”);
onmouseout=new Function(“stopscroll=false”);
}
document.write(‘<div id=”templayer1″ style=”position:absolute;z-index:1;visibility:hidden;top:6px;”></div>’);preTop=0; currentTop=0;
function init1(){
templayer1.innerHTML=”";
while(templayer1.offsetHeight<marqueesHeight){
templayer1.innerHTML+=flash.innerHTML;
}
flash.innerHTML=templayer1.innerHTML+templayer1.innerHTML;
setInterval(“scrollUp1()”,20);//?
}
document.body.onload=init1;function scrollUp1(){
if(stopscroll==true) return;
preTop=flash.scrollTop;
flash.scrollTop+=1;
if(preTop==flash.scrollTop){
flash.scrollTop=templayer1.offsetHeight-marqueesHeight;
flash.scrollTop+=1;
}
}
</SCRIPT>
這其實就是很普通的輪播。造成不相容的原因,是程式碼寫得不够完善。下面我給出我的解決方案:
<SCRIPT language=JavaScript>
marqueesHeight=550;
stopscroll=false;
var marquees=document.getElementById(“flash”);
var templayer=document.getElementById(“templayer1″);
with(flash){
flash.style.width=235+”px”;
flash.style.height=marqueesHeight+”px”;
flash.style.overflowX=”visible”;
flash.style.overflowY=”hidden”;
flash.noWrap=true;
flash.onmouseover=new Function(“stopscroll=true”);
flash.onmouseout=new Function(“stopscroll=false”);
}
document.write(‘<div id=”templayer1″ style=”position:absolute;z-index:1;visibility:hidden;top:6px;”></div>’);
var preTop=0; currentTop=0;
function init1(){
templayer1.innerHTML=”";
while(templayer1.offsetHeight<marqueesHeight){
templayer1.innerHTML+=flash.innerHTML;
}
flash.innerHTML=templayer1.innerHTML+templayer1.innerHTML;
setInterval(“scrollUp1()”,10);//?
}
window.onload=init1;
function scrollUp1(){
if(stopscroll==true) return;
preTop=flash.scrollTop;
flash.scrollTop+=1;
if(preTop==flash.scrollTop){
flash.scrollTop=templayer1.offsetHeight-marqueesHeight;
flash.scrollTop+=1;
}
}
</SCRIPT>
把程式碼寫完善,不僅會更相容,也會更好看。我們寫程式,千萬不要貪圖一時的快,要寫出好程式,就不能出現上面那樣的問題。