如何使用Javascript检测元素的文本方向

How to detect text direction of element using Javascript?

本文关键字:文本 方向 元素 检测 何使用 Javascript      更新时间:2023-09-26

使用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
http://jsfiddle.net/m8Zwk/

getComputedStyle在Mozilla Developer Network上的参考

试试这个

document.defaultView.getComputedStyle(document.getElementById('baz'),null)['direction'];

style = document.defaultView.getComputedStyle(document.firstChild,null);
console.log(style.direction);

@ explosive -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的第二个参数。

既然这提供了更多的信息,我想我应该把它贴出来,以防它对别人有帮助。

您可以简单地使用style对象:

console.log(document.getElementById('baz').style.direction);

请注意,这个DOM对象只表示元素的内联样式,它不适用于任何css样式表。