如何使用Javascript检测HTML元素的文本方向?我期望得到"rtl"或"ltr"之一。
<div dir="ltr" id="foo">bar</div>
<div style="direction:ltr" id="baz">quux</div>
<div dir="ltr"><div id="jeez">whiz</div></div>
如何测试“foo”、“baz”或“jeez”的方向?
如何使用Javascript检测HTML元素的文本方向?我期望得到"rtl"或"ltr"之一。
<div dir="ltr" id="foo">bar</div>
<div style="direction:ltr" id="baz">quux</div>
<div dir="ltr"><div id="jeez">whiz</div></div>
如何测试“foo”、“baz”或“jeez”的方向?
getComputedStyle
在现代浏览器中可用(包括IE9+和其他浏览器)。
getComputedStyle(document.getElementById('foo')).direction
试试这个
document.defaultView.getComputedStyle(document.getElementById('baz'),null)['direction'];
或者
style = document.defaultView.getComputedStyle(document.firstChild,null);
console.log(style.direction);
@explosion-pills的答案是正确的。我为了兼容IE做了更多的研究,得出以下结论:
function getDirection(el) {
var dir;
if (el.currentStyle)
dir = el.currentStyle['direction'];
else if (window.getComputedStyle)
dir = getComputedStyle(el, null).getPropertyValue('direction');
return dir;
}
这甚至可以在Firefox 3.6上运行,该浏览器要求将null
作为getPropertyValue
的第二个参数。
由于这提供了更多信息,我想发布它以帮助他人。