2011-06-04 104 views
0

我需要純JavaScript功能,它可以找到HTML元素的當前不透明度並將其降低10%。有沒有有效的跨瀏覽器解決方案?如何減少CSS的不透明度

請不要JS框架像jQuery(我有我的理由,所以不要問爲什麼),謝謝。

回答

1

隨着IE變化

var style = document.getElementById(...).style; 
if(browserIsIE) { 
    var regExpResult = /alpha\(opacity\s*=\s*(\d*)\s*\)/.exec(style.filter); 
    var opacity; 
    if(regExpResult && regExpResult.constructor == Array && regExpResult[1] && opacity = parseInt(regExpResult[1])) { 
    style.filter = "alpha(opacity = " + (opacity - 10) + ")"; 
    } else { 
    style.filter = "alpha(opacity = 90)"; 
    } 
} else { 
    style.opacity = style.opacity=='' ? 0.9 : parseFloat(style.opacity)-0.1; 
} 
+0

+1這是非常有前途的,但你破壞了其他過濾器,看看我的筆記[這裏](HTTP ://sackoverflow.com/questions/5259824/how-to-add-alpha-filter-to-any-html-element-and-keep-the-other-filters-in-ie/5261807#5261807) – 2011-06-04 08:09:57

0
var style = document.getElementById(...).style; 
style.opacity = style.opacity=='' ? 0.9 : parseFloat(style.opacity)-0.1; 

返回值可能需要手動轉換成一個字符串,我忘了。

+0

OK,但這不會在IE瀏覽器,我想 – 2011-06-04 07:09:13

0

我迄今取得這一進展。你可以請測試或微調它嗎?

function normOpacity(num,ie) { 
    num = parseFloat(num); 
    if(num<0) return 0; 
    if(num>1 && !ie) return 1; 
    if(num>100 && ie) return 100; 
    return num; 
} 

function changeOpacity(obj,diff) { 
    if(!obj) return; 
    if(!obj.filters) { 
    var gcs = document.defaultView.getComputedStyle(obj,null); 
    var op = parseFloat(gcs.getPropertyValue("opacity")) + diff; 
    return obj.style.opacity = normOpacity(op)+""; 
    } 
    if(!obj.style.zoom) obj.style.zoom = 1; 
    var op, al, dx = "DXImageTransform.Microsoft."; 
    try { al = obj.filters.item(dx+"Alpha"); } catch(e) {} 
    if(!al) try { al = obj.filters.item("Alpha"); } catch(e) {} 
    if(!al) { 
    var op = normOpacity(100+100*diff,true); 
    return obj.style.filter+= "progid:"+dx+"Alpha(opacity="+op+")"; 
    } 
    try { op = al["Opacity"]; } catch(e) { op = 100; } 
    al["Opacity"] = normOpacity(parseInt(op)+100*diff,true)+""; 
} 

使用

changeOpacity(obj,-0.1); // opacity should be 10% lower, regardless the browser 
+0

會做。到現在爲止還是在城外。 – 2011-06-08 06:09:41

相關問題