admin管理员组文章数量:1202781
What's the best way to detect the text direction of an html element using Javascript? I would expect to get either "rtl" or "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>
How would I test for the direction on "foo", "baz" or "jeez"?
What's the best way to detect the text direction of an html element using Javascript? I would expect to get either "rtl" or "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>
How would I test for the direction on "foo", "baz" or "jeez"?
Share Improve this question edited Jun 5, 2013 at 12:26 j0k 22.8k28 gold badges81 silver badges90 bronze badges asked Mar 31, 2013 at 3:19 choweychowey 9,8266 gold badges57 silver badges86 bronze badges3 Answers
Reset to default 24getComputedStyle
is available in modern browsers (IE9+ and the others). Use it like this:
getComputedStyle(document.getElementById("foo")).direction
Here's a full example:
for (let id of ["foo", "baz", "jeez", "hello"]) {
console.log(id, getComputedStyle(document.getElementById(id)).direction);
}
<div dir="ltr" id="foo">bar</div>
<div style="direction:ltr" id="baz">quux</div>
<div dir="ltr"><div id="jeez">whiz</div></div>
<div dir="auto" id="hello">hello</div>
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.
本文标签: htmlHow to detect text direction of element using JavascriptStack Overflow
版权声明:本文标题:html - How to detect text direction of element using Javascript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738587183a2101496.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论