【问题标题】:Style only elements with `direction: rtl`仅使用 `direction: rtl` 样式化元素
【发布时间】:2020-10-23 16:17:43
【问题描述】:

假设我遇到了如下问题。有没有办法只使用 CSS 来选择,只有 direction: rtl 样式的元素?提前致谢!

.rightToLeft {
  direction: rtl;
}

.leftToRight {
  direction: ltr;
}

/* Is there is any simple way to select all of the 3 different spans with the dirction=rtl property? */
<span class="rightToLeft">This is RtL, </span>
<span class="letfToRight">and this is LtR!</span> (: <br/>

<span dir="rtl">This is RtL too,</span>
<span style="direction: rtl;">and this one also! </span>

我已阅读this answer,但它仅在元素内部给出给定属性时才有效,而不是通过 CSS 类(前两个示例)。

【问题讨论】:

    标签: html css


    【解决方案1】:

    你需要 3 条规则:类、属性和属性内容。

    .rightToLeft {
      direction: rtl;
    }
    
    .leftToRight {
      direction: ltr;
    }
    
    .rightToLeft, *[dir='rtl'], *[style*='direction: rtl']{
      color: green;
    }
    
    /* Is there is any simple way to select all of the 3 different spans with the dirction=rtl property? */
    <span class="rightToLeft">This is RtL, </span>
    <span class="letfToRight">and this is LtR!</span> (: <br/>
    
    <span dir="rtl">This is RtL too,</span>
    <span style="direction: rtl;">and this one also! </span>

    【讨论】:

    • 我正在寻找一种方法来选择“rightToLeft”类而不实际使用它(只需搜索方向属性)。这可能吗?
    • 您可以只使用*[dir='rtl'], *[style*='direction: rtl']{ ... } 来选择元素而不使用类名。你选择这些元素的意图是什么?这些属性中的任何一个都不包括通过 javascript (element.style.direction='rtl') 设置样式。在这种情况下,您必须使用 javascript getComputedStyle() 来获取当前呈现的样式。
    【解决方案2】:

    您可以使用逗号分隔符选择器:

      .right-to-left, *[style*="direction:rtl"], *[dir="rtl"]{
            //your style...
        }
    

    我将 rightToLeft 更改为 从右到左。用于 CSS 类中的命名约定。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多