I am trying to write a test to work out whether the text rendered inside an <input>
has the same baseline as a label:
In order to do this, I would like to compute the baseline of the text that has been rendered in each element and compare the two values. Is this possible and if so, how is it done? If not, is there a better way to establish that the baseline of the two elements is the same?
I have found a way to determine the baseline of the label which seems to work reliably:
function getBaseline(element) {
var span = document.createElement("span");
span.setAttribute("style", "font-size:0");
span.innerText = "A";
jQuery(element).prepend(span);
return span.getBoundingClientRect().bottom;
}
However, this method doesn't work for the <input>
, as I cannot insert the span in that case.
I found a way to get the computed baseline based on your function. The trick is to create a wrapper and apply all styles from the element to it. I can confirm that it works in Firefox (v38) and Chrome (v44) on OSX. Unfortunately it doesn't work proper in Safari.
DEMO
function getBaseline(element) {
element = jQuery(element);
var span = document.createElement("span");
span.setAttribute("style", "font-size:0");
span.innerText = "A";
var wrapper = document.createElement("span");
applyCSSProperties.call(wrapper, element);
element.wrap(wrapper);
element.before(span);
var computed = span.getBoundingClientRect().bottom;
span.remove();
element.unwrap(wrapper);
return computed;
}
function applyCSSProperties(element) {
var styles = {};
var comp = getComputedStyle(element[0]);
for(var i = 0; i < comp.length; i++){
styles[comp[i]] = comp.getPropertyValue(comp[i]);
}
jQuery(this).css(styles);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With