js與自動伸縮圖片 自動縮小圖片的多瀏覽器兼容的方法總結 原創
2024-09-06 12:42:59
供稿:網友
最近做一個圖片的自動縮小效果,發現一直用的js,竟然在firefox下無法正常啊,導致頁面變形.所以自己寫了個兼容性一般的代碼,大家可以來討論下
原來我用的是從pjblog上的
代碼如下:
//查找網頁內寬度太大的圖片進行縮放以及PNG糾正
function ReImgSize(){
for (i=0;i<document.images.length;i++)
{
if (document.all){
if (document.images[i].width>550)
{
document.images[i].width="550" //沒有高,明顯會讓圖片變形
try{
document.images[i].outerHTML='<a href="'+document.images[i].src+'" target="_blank" title="在新窗口打開圖片">'+document.images[i].outerHTML+'</a>'
}catch(e){}
}
}
else{
if (document.images[i].width>400) {
//寬和高都沒有,更是讓firefox下圖片撐大圖片
document.images[i].title="在新窗口打開圖片"
document.images[i].style.cursor="pointer"
document.images[i].onclick=function(e){window.open(this.src)}
}
}
}
}
非常好用的代碼可不足的地方就是firefox下大圖會變形,而且無法控制區域的圖片,如果想要的大圖,也被變成小圖了
我自己寫了個,
代碼如下:
function $(objectId) {
if(document.getElementById && document.getElementById(objectId)) {
// W3C DOM
return document.getElementById(objectId);
}
else if (document.all && document.all(objectId)) {
// MSIE 4 DOM
return document.all(objectId);
}
else if (document.layers && document.layers[objectId]) {
// NN 4 DOM.. note: this won't find nested layers
return document.layers[objectId];
}
else {
return false;
}