Grant Wagner wrote:
Konrad Den Ende wrote:
I have a function returning a string but the problem is that the
color of it is blue which suits me well for some pages but not for
others. Is it possible to "feel" what the color of the background
in the current document is and set the color of the output
accordingly? The background will be an image, in most cases.
<body onload="alert(getCurrentStyle());">
<script type="text/javascript">
function getCurrentStyle() {
if (document.defaultView && document.defaultView.getComputedStyle &&
document.body) {
var computedStyle =
document.defaultView.getComputedStyle(document.bod y, null);
return 'computedStyle = ' +
computedStyle.getPropertyValue('background-color');
} else if (document.body && document.body.currentStyle) {
return 'currentStyle = ' +
document.body.currentStyle.backgroundColor; } else if
(document.bgColor) { return 'bgColor = ' + document.bgColor;
}
}
</script>
</body>
If you run this in Opera 7.51 and Gecko-based browsers (Netscape 7,
Mozilla, Firefox, Camino), you get "transparent", unfortunately, in
IE6SP1 and Netscape 4 you get "#ffffff".
Even if you set a background color using CSS: "body {
background-color:Blue; }" there are some differences. IE6SP1 shows
"blue", however Gecko-based browsers report "rgb(0, 0, 255)" and
Opera 7.51 and Netscape 4.78 display "#0000ff"
In other words, determining the background color of the page in a
cross-browser compatible way is not as simple as it first appears.
<snip>
Another line of attack using - document.defaultView.getComputedStyle -
is to get an object implementing the - CSSValue - interface using the
computed style object's - getPropertyCSSValue - method (not implemented
in Opera 7 but available on Mozilla/Gecko and Konqueror/Safari):-
var cs = document.defaultView.getComputedStyle(el, null);
var CSSValue = cs.getPropertyCSSValue('background-color');
The returned CSSValue object (may be null, check it is not null before
use) has a - cssValueType - numeric property that corresponds with one
of 4 defined constants:-
CSS_INHERIT == 0
CSS_PRIMITIVE_VALUE == 1
CSS_VALUE_LIST == 2
CSS_CUSTOM == 3
If the object is CSS_PRIMITIVE_VALUE type it also implements the -
CSSPrimitiveValue
- interface. The - CSSPrimitiveValue - interface has a numeric property
called - primitiveType - that corresponds with another set of specified
constants including:-
CSS_IDENT == 21
CSS_RGBCOLOR == 25
A background color should be one of these two types. If it is CSS_IDENT
the value is likely to be "transparent". If it is CSS_RGBCOLOR then a -
getRGBColorValue - method may be called on the object to retrieve an
instance of the - RGBColor - interface.
var RGBColor = CSSValue.getRGBColorValue();
- which has properties - red, green and blue - that each refer to
objects implementing - CSSPrimitiveValue -. In the case of these objects
the likely - primitiveType - values are:-
CSS_NUMBER == 1
CSS_PERCENTAGE == 2
With CSS_NUMBER being the type used on Mozilla. In the W3C CSS DOM
specification it says that it should be possible to retrieve the value
in either form, but Mozilla only allows the value to be acquired as a
CSS_NUMBER. Retrieving the value is done with the - getFloatValue -
method passing the type as its argument. CSS_NUMBER values are in the
range 0 to 255.
var redValue = RGBColor.red.getFloatValue(1);
var blueValue = RGBColor.blue.getFloatValue(1);
var greenValue = RGBColor.green.getFloatValue(1);
- but that might be implemented as:-
var type = RGBColor.red.primitiveType;
var redValue = RGBColor.red.getFloatValue(type)*((type == 2)?2.55:1);
- to allow for the possibility that the value may be a percentage
instead of a number in the range 0 to 255.
In principle the future should see these interfaces more widely
implemented and for the retrieval of color values they are probably
simpler to use than the examination of all of the permutations of string
values that might be available, followed by the extraction of the
contained color information.
Indeed I was recently forced to pursue these interfaces because it
turned out that Konqueror 3 has made the strange decision of returning,
for example, "border-right-width:4px" instead of "4px" from:-
cs.getPropertyValue('border-right-width');
- which means passing the result through - parseInt - returns NaN
instead of the width of the border in pixels.
I did some experiments to see what was available form computed style
objects on various browsers. The following are the functions I was using
for the task; passing the - getComputedCSSInfo - function an element
reference as its argument returns a string describing what information
is available form the computed style object, which can be written into a
textarea, for example:-
function getComputedCSSInfo(element){
var indent = '\n';
var temp,cs,defaultView,text = '';
if(element){
if(element.tagName){
text += '<'+element.tagName+'>\n';
}else if(element.nodeName){
text += 'Node Name == ['+element.nodeName+']\n';
}
if(element.nodeType){
text += 'Node Type == '+nodeType_names[element.nodeType]+'\n';
}
if(element.id){
text += 'ID == \"'+element.id+'\"\n';
}
if(element.className){
text += 'className == \"'+element.className+'\"\n';
}
if((defaultView = document.defaultView)&&
(defaultView.getComputedStyle) &&
(cs = defaultView.getComputedStyle(element, null))
){
for(var c = 0;c < CSSProprety_names.length;c++){
temp = cs.getPropertyValue(CSSProprety_names[c]);
if(typeof temp != 'undefined'){
text += indent + 'String value from - getPropertyValue(\''+
CSSProprety_names[c]+'\') == \"'+temp+'\"';
}
if( cs.getPropertyCSSValue){
temp = cs.getPropertyCSSValue(CSSProprety_names[c]);
if(temp){
text += indent +
'CSSValue object from - getPropertyCSSValue(\''+
CSSProprety_names[c]+'\') == ';
text += CSSValueReport(temp, (indent+'\t'));
}
}
if(typeof temp != 'undefined'){text += indent;}
}
}else if(element.currentStyle){
for(var c = 0;c < CSSStyleProperties_names.length;c++){
temp = element.currentStyle[CSSStyleProperties_names[c]];
if(typeof temp != 'undefined'){
text += indent +
'String value from - element.currentStyle.'+
CSSStyleProperties_names[c]+' == \"'+temp+'\"';
text += indent;
}
}
}
}
return text;
}
function CSSValueReport(cssValue, indent){
var type = cssValue.cssValueType;
var st = indent+'CSSValue Type == '+type+' -> '+
(CSSValueType_names[type]||'not a specified type');
switch(type){
case 0: //CSS_INHERIT
st += indent+'The value is inherited : data == '+
cssValue.cssText;
break;
case 1: //CSS_PRIMITIVE_VALUE
st += CSSPrimativeReport(cssValue, (indent+'\t'));
break;
case 2: //CSS_VALUE_LIST
for(var c = 0;c < cssValue.length;c++){
st += indent+'Item == '+c;
st += CSSValueReport(cssValue.item(c), (indent+'\t'));
}
break;
case 3: //CSS_CUSTOM
st += indent+'The value is a custom value : data == '+
cssValue.cssText;
break;
default:
break;
}
return st;
}
function CSSPrimativeReport(cssValue, indent){
var temp,type = cssValue.primitiveType;
var st = indent+'CSSPrimitiveValue Type == '+type+' -> '+
(CSSPrimativeType_names[type]||'not a specified type');
switch(type){
case 0: //CSS_UNKNOWN
st += indent+
'Value is not a recognized CSS2 value: data == '+
cssValue.cssText;
break;
case 18: //CSS_DIMENSION
case 1: //CSS_NUMBER
case 2: //CSS_PERCENTAGE
case 3: //CSS_EMS
case 4: //CSS_EXS
case 5: //CSS_PX
case 6: //CSS_CM
case 7: //CSS_MM
case 8: //CSS_IN
case 9: //CSS_PT
case 10: //CSS_PC
st += indent+'Float value is == '+
cssValue.getFloatValue(type);
st += tryLengthConversion(cssValue, (indent+'\t'));
break;
case 11: //CSS_DEG
case 12: //CSS_RAD
case 13: //CSS_GRAD
case 14: //CSS_MS
case 15: //CSS_S
case 16: //CSS_HZ
case 17: //CSS_KHZ
st += indent+'Float value is == '+
cssValue.getFloatValue(type);
st += tryOtherConversion(cssValue, (indent+'\t'));
break;
case 19: //CSS_STRING
case 20: //CSS_URI
case 21: //CSS_IDENT
case 22: //CSS_ATTR
st += indent+'String value is == \"'+
cssValue.getStringValue()+'\"';
break;
case 23: //CSS_COUNTER
temp = cssValue.getCounterValue();
st += indent+'Counter.identifier == '+temp.identifier;
st += indent+'Counter.listStyle == '+temp.listStyle;
st += indent+'Counter.separator == '+temp.separator;
break;
case 24: //CSS_RECT
temp = cssValue.getRectValue();
st += indent+'Rect.top == '+
CSSPrimativeReport(temp.top, (indent+'\t'));
st += indent+'Rect.left == '+
CSSPrimativeReport(temp.left, (indent+'\t'));
st += indent+'Rect.bottom == '+
CSSPrimativeReport(temp.bottom, (indent+'\t'));
st += indent+'Rect.rigth == '+
CSSPrimativeReport(temp.right, (indent+'\t'));
break;
case 25: //CSS_RGBCOLOR
temp = cssValue.getRGBColorValue();
st += indent+'RGBColor.red == '+
CSSPrimativeReport(temp.red, (indent+'\t'));
st += indent+'RGBColor.green == '+
CSSPrimativeReport(temp.green, (indent+'\t'));
st += indent+'RGBColor.blue == '+
CSSPrimativeReport(temp.blue, (indent+'\t'));
break;
default:
break;
}
return st;
}
function tryLengthConversion(cssValue, indent){
var temp,type = cssValue.primitiveType;
var st = indent+'Length Values -> ';
try{ //CSS_NUMBER
st += indent+'CSS_NUMBER value == '+cssValue.getFloatValue(1);
}catch(e){
st += indent+'Cannot Convert to CSS_NUMBER (exception)';
}
try{ //CSS_PERCENTAGE
st += indent+'CSS_PERCENTAGE value == '+
cssValue.getFloatValue(2);
}catch(e){
st += indent+'Cannot Convert to CSS_PERCENTAGE (exception)';
}
try{ //CSS_EMS
st += indent+'CSS_EMS value == '+ cssValue.getFloatValue(3);
}catch(e){
st += indent+'Cannot Convert to CSS_EMS (exception)';
}
try{ //CSS_EXS
st += indent+'CSS_EXS value == '+ cssValue.getFloatValue(4);
}catch(e){
st += indent+'Cannot Convert to CSS_EXS (exception)';
}
try{ //CSS_PX
st += indent+'CSS_PX value == '+ cssValue.getFloatValue(5);
}catch(e){
st += indent+'Cannot Convert to CSS_PX (exception)';
}
try{ //CSS_CM
st += indent+'CSS_CM value == '+ cssValue.getFloatValue(6);
}catch(e){
st += indent+'Cannot Convert to CSS_CM (exception)';
}
try{ //CSS_MM
st += indent+'CSS_MM value == '+ cssValue.getFloatValue(7);
}catch(e){
st += indent+'Cannot Convert to CSS_MM (exception)';
}
try{ //CSS_IN
st += indent+'CSS_IN value == '+ cssValue.getFloatValue(8);
}catch(e){
st += indent+'Cannot Convert to CSS_IN (exception)';
}
try{ //CSS_PT
st += indent+'CSS_PT value == '+ cssValue.getFloatValue(9);
}catch(e){
st += indent+'Cannot Convert to CSS_PT (exception)';
}
try{ //CSS_PC
st += indent+'CSS_PC value == '+ cssValue.getFloatValue(10);
}catch(e){
st += indent+'Cannot Convert to CSS_PC (exception)';
}
return st;
}
function tryOtherConversion(cssValue, indent){
var temp,type = cssValue.primitiveType;
var st = indent+'Values -> ';
try{ //CSS_DEG
st += indent+'CSS_DEG value == '+ cssValue.getFloatValue(11);
}catch(e){
st += indent+'Cannot Convert to CSS_DEG (exception)';
}
try{ //CSS_RAD
st += indent+'CSS_RAD value == '+ cssValue.getFloatValue(12);
}catch(e){
st += indent+'Cannot Convert to CSS_RAD (exception)';
}
try{ //CSS_GRAD
st += indent+'CSS_GRAD value == '+ cssValue.getFloatValue(13);
}catch(e){
st += indent+'Cannot Convert to CSS_GRAD (exception)';
}
try{ //CSS_MS
st += indent+'CSS_MS value == '+ cssValue.getFloatValue(14);
}catch(e){
st += indent+'Cannot Convert to CSS_MS (exception)';
}
try{ //CSS_S
st += indent+'CSS_S value == '+ cssValue.getFloatValue(15);
}catch(e){
st += indent+'Cannot Convert to CSS_S (exception)';
}
try{ //CSS_HZ
st += indent+'CSS_HZ value == '+ cssValue.getFloatValue(16);
}catch(e){
st += indent+'Cannot Convert to CSS_HZ (exception)';
}
try{ //CSS_KHZ
st += indent+'CSS_KHZ value == '+ cssValue.getFloatValue(17);
}catch(e){
st += indent+'Cannot Convert to CSS_KHZ (exception)';
}
return st;
}
var CSSValueType_names = ['CSS_INHERIT','CSS_PRIMITIVE_VALUE',
'CSS_VALUE_LIST','CSS_CUSTOM'];
var CSSPrimativeType_names = ['CSS_UNKNOWN','CSS_NUMBER',
'CSS_PERCENTAGE','CSS_EMS','CSS_EXS','CSS_PX','CSS _CM','CSS_MM',
'CSS_IN','CSS_PT','CSS_PC','CSS_DEG','CSS_RAD','CS S_GRAD',
'CSS_MS','CSS_S','CSS_HZ','CSS_KHZ','CSS_DIMENSION ','CSS_STRING',
'CSS_URI','CSS_IDENT','CSS_ATTR','CSS_COUNTER','CS S_RECT',
'CSS_RGBCOLOR'];
var CSSProprety_names = [
'azimuth','background','background-attachment','background-color',
'background-image','background-position','background-repeat',
'border','border-collapse','border-color','border-spacing',
'border-style','border-top','border-right','border-bottom',
'border-left','border-top-color','border-right-color',
'border-bottom-color','border-left-color','border-top-style',
'border-right-style','border-bottom-style','border-left-style',
'border-top-width','border-right-width','border-bottom-width',
'border-left-width','border-width','bottom','caption-side',
'clear','clip','color','content','counter-increment',
'counter-reset','cue','cue-after','cue-before','cursor',
'direction','display','elevation','empty-cells','float','font',
'font-family','font-size','font-size-adjust','font-stretch',
'font-style','font-variant','font-weight','height','left',
'letter-spacing','line-height','list-style','list-style-image',
'list-style-position','list-style-type','margin','margin-top',
'margin-right','margin-bottom','margin-left','marker-offset',
'marks','max-height','max-width','min-height','min-width',
'orphans','outline','outline-color','outline-style',
'outline-width','overflow','padding','padding-top',
'padding-right','padding-bottom','padding-left','page',
'page-break-after','page-break-before','page-break-inside',
'pause','pause-after','pause-before','pitch','pitch-range',
'play-during','position','quotes','richness','right','si ze',
'speak','speak-header','speak-numeral','speak-punctuation',
'speech-rate','stress','table-layout','text-align',
'text-decoration','text-indent','text-shadow','text-transform',
'top','unicode-bidi','vertical-align','visibility','voice-family',
'volume','white-space','widows','width','word-spacing','z-index'
];
var CSSStyleProperties_names = [
'azimuth','background','backgroundAttachment','bac kgroundColor',
'backgroundImage','backgroundPosition','background Repeat','border',
'borderCollapse','borderColor','borderSpacing','bo rderStyle',
'borderTop','borderRight','borderBottom','borderLe ft',
'borderTopColor','borderRightColor','borderBottomC olor',
'borderLeftColor','borderTopStyle','borderRightSty le',
'borderBottomStyle','borderLeftStyle','borderTopWi dth',
'borderRightWidth','borderBottomWidth','borderLeft Width',
'borderWidth','bottom','captionSide','clear','clip ',
'color','content','counterIncrement','counterReset ',
'cue','cueAfter','cueBefore','cursor','direction', 'display',
'elevation','emptyCells','cssFloat','font','fontFa mily',
'fontSize','fontSizeAdjust','fontStretch','fontSty le','fontVariant',
'fontWeight','height','left','letterSpacing','line Height',
'listStyle','listStyleImage','listStylePosition',' listStyleType',
'margin','marginTop','marginRight','marginBottom', 'marginLeft',
'markerOffset','marks','maxHeight','maxWidth','min Height',
'minWidth','orphans','outline','outlineColor','out lineStyle',
'outlineWidth','overflow','padding','paddingTop',' paddingRight',
'paddingBottom','paddingLeft','page','pageBreakAft er',
'pageBreakBefore','pageBreakInside','pause','pause After',
'pauseBefore','pitch','pitchRange','playDuring','p osition',
'quotes','richness','right','size','speak','speakH eader',
'speakNumeral','speakPunctuation','speechRate','st ress',
'tableLayout','textAlign','textDecoration','textIn dent',
'textShadow','textTransform','top','unicodeBidi',' verticalAlign',
'visibility','voiceFamily','volume','whiteSpace',' widows',
'width','wordSpacing','zIndex'
];
var nodeType_names = ['','ELEMENT_NODE','ATTRIBUTE_NODE','TEXT_NODE',
'CDATA_SECTION_NODE','ENTITY_REFERENCE_NODE','ENTI TY_NODE',
'PROCESSING_INSTRUCTION_NODE','COMMENT_NODE','DOCU MENT_NODE',
'DOCUMENT_TYPE_NODE','DOCUMENT_FRAGMENT_NODE','NOT ATION_NODE'];
Richard.