How to detect text direction of element using Javascript?

a 夏天 提交于 2019-12-03 04:00:55
Explosion Pills

getComputedStyle is available in modern browsers (IE9+ and the others).

getComputedStyle(document.getElementById('foo')).direction

http://jsfiddle.net/m8Zwk/

Reference to getComputedStyle on Mozilla Developer Network

Try this

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

OR

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

@explosion-pills answer is correct. I did some more research for IE compatibility and came up with the following:

function getDirection(el) {
    var dir;
    if (el.currentStyle)
        dir = el.currentStyle['direction'];
    else if (window.getComputedStyle)
        dir = getComputedStyle(el, null).getPropertyValue('direction');
    return dir;
}

This should even work on Firefox 3.6 which requires null as the second parameter to getPropertyValue.

Since this gives more information I thought I would post it in case it helps someone.

You can simply use the style object:

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

DEMO

Take note that this object of the DOM only represents the in-line styles of an element, it doesn't apply to any css style sheets.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!