Say we want an image to have 25% transparency...
The standard CSS property is
opacity: 0.25;
but IE and some older browsers have different ways of specifying it, so you probably want to use them all to cover your bases
opacity: 0.25; //css standard
filter:alpha(opacity=25); //ie (note that 50% is 25 here, not .25)
-moz-opacity:0.25; //very old mozilla/netscape browsers
-khtml-opacity: 0.25; //very old safari browsers
Here is what it might look like in GWT
public void setOpacity(Element element, double opacity) {
if (opacity > .995) {
element.getStyle().setProperty("opacity", "");
element.getStyle().setProperty("filter", "");
element.getStyle().setProperty("-moz-opacity", "");
element.getStyle().setProperty("-khtml-opacity", "");
} else {
String s = Integer.toString((int) Math.round(opacity * 100));
String sDecimal = (s.length() == 1 ? ".0" : ".") + s;
element.getStyle().setProperty("opacity", sDecimal);
element.getStyle().setProperty("filter", "alpha(opacity=" + s + ")");
element.getStyle().setProperty("-moz-opacity", sDecimal);
element.getStyle().setProperty("-khtml-opacity", sDecimal);
}
}
Thanks!!! Excellent post, pretty helpful one. One note: attempting to set a "-moz-opacity" property threw me a javascript invocation error. I suggest the code is modified following way:
ReplyDeleteprivate static void setProperty_NoFail(Style style, String propertyName, String propertyValue) {
try {
style.setProperty(propertyName, propertyValue);
} catch (Throwable exc) {
// nothing
}
}
public static void setOpacity(Element element, double opacity) {
Style style = element.getStyle();
if (opacity > .995) {
setProperty_NoFail(style, "opacity", "");
setProperty_NoFail(style, "filter", "");
setProperty_NoFail(style, "-moz-opacity", "");
setProperty_NoFail(style, "-khtml-opacity", "");
} else {
String s = Integer.toString((int) Math.round(opacity * 100));
String sDecimal = (s.length() == 1 ? ".0" : ".") + s;
setProperty_NoFail(style, "opacity", sDecimal);
setProperty_NoFail(style, "filter", "alpha(opacity=" + s + ")");
setProperty_NoFail(style, "-moz-opacity", sDecimal);
setProperty_NoFail(style, "-khtml-opacity", sDecimal);
}
}