我想知道如何在chrome浏览器中实现此代码,
/* Selects any element with right-to-left text */
:dir(rtl) {
background-color: red;
}https://developer.mozilla.org/en-US/docs/Web/CSS/:dir在Chrome浏览器中有什么替代方案?
发布于 2021-10-11 15:05:33
由于您使用的是dir HTML attribute,因此可以使用CSS attribute selector来相应地设置该元素的样式。所有现代浏览器都广泛支持属性选择器。
对于Chrome,您可能需要将元素应用于<body>,或者准备使用body { background-color: inherit; }
html[dir="rtl"] {
background-color: red;
}
body {
background-color: inherit; /* Required for Chrome */
}<html dir="rtl">
<body>
<div>A red document background</div>
</body>
</html>
当然,您也不必将其应用于整个文档。您只能将其应用于特定元素:
div[dir="rtl"] {
background-color: red;
}<html>
<body>
<div>A white background</div>
<div dir="rtl">A red background</div>
</body>
</html>
如果你想使用JavaScript来检测dir属性,你可以这样做(或者使用你最喜欢的方法通过JS来检测元素……至少有半打不同的方法):
/* EcmaScript 6 required, which shouldn't be an issue for modern Chrome, Firefox, Edge, etc. */
const doc = document.querySelector('html');
if (doc.hasAttribute('dir')) {
const textDir = doc.getAttribute('dir');
if (textDir == 'rtl') {
doc.classList.add('rtl');
} else {
doc.classList.add('ltr');
}
}.rtl {
background-color: red;
}
body {
background-color: inherit; /* again, only needed for Chrome */
}
.ltr {
/* whatever styles you want for LTR text direction */
background-color: green;
}<html dir="rtl">
<body>
<div>A red document background</div>
</body>
</html>
发布于 2022-02-12 23:41:50
:dir()确实非常有用,因为它表示元素的方向,即使是继承自父代或祖先,但不幸的是,它只在你提到的火狐中才受支持。
[dir="rtl"]是跨浏览器支持的,但它只引用具有这种特性的元素。如果整个文档是一个方向,并且它是在<html>或<body>标记中指定的,那么这不是一个大问题,因为您可以简单地使用子选择器。例如
[dir="rtl"] p {
background: red;
}但是,在包含嵌套部分的双向文档中,这会变得复杂。例如
<body dir="rtl">
<p>עברית (RTL text)</p>
<div dir="ltr">
<p>English (LTR text)</p>
<div dir="rtl">
<p>עברית (another RTL text)</p>
</div>
</div>
</body>当然,您可以将样式规则应用于两个方向,如下所示
[dir="ltr"] p {
background: green;
}
[dir="rtl"] p {
background: red;
}但是CSS并不关心哪个祖先更接近,所以上面的代码仍然会将red应用于所有段落(甚至颠倒规则的顺序对嵌套部分也没有帮助)。
在这种情况下,您可以使用继承的CSS变量。例如
[dir="ltr"] {
--p-background: green;
}
[dir="rtl"] {
--p-background: red;
}
p {
background: var(--p-background);
}在这种情况下,变量直接应用于具有指定方向的元素,然后像方向本身一样通过元素链继承变量值,并影响定义为使用变量值的元素的样式-在本例中为<p>元素。
https://stackoverflow.com/questions/69528290
复制相似问题