如何通过JS更改CSS类样式

时间:2020-06-10 17:43:07

标签: javascript

我有这样的css clas:

.title-bottom:before {
    bottom: -5px;
    content: "";
    height: 2px;
    left: 0;
    position: absolute;
    width: 80px;
}

left:0将下划线设置为左,但是当RTL处于活动状态时,它必须向右浮动。因此,我想将rtl存在的情况下将left:0改为left:initial。

我该怎么办?我开始写这样的代码:

if (document.dir === 'rtl'){

但是我无法继续。因为我找不到学习JS的好资源。

我需要一个代码来解决这个问题,也是学习JS的良好资源。

1 个答案:

答案 0 :(得分:0)

您要更改整个文档的CSS规则。

执行此操作的一种方法是将样式表附加到文档的<head>,然后在其中放置规则更改。由于添加的样式表是文档中的最后一个样式表,因此它将覆盖默认规则。

if (document.dir === 'rtl') {

  // create a new style sheet and append to head
  let newStyle = document.createElement('style');
  newStyle.innerHTML = '.title-bottom:before { left:initial; }';
  document.head.appendChild(newStyle);
}

function addRtl() {
  let newStyle = document.createElement('style');
  newStyle.innerHTML = '.title-bottom:before { content: ".rtl"; }';
  document.head.appendChild(newStyle);
  document.dir = 'rtl';
}
.title-bottom {
  background-color: lightgray;
  padding: 1rem;
}
<body>
<h1>RTL Style Manipulation</h1>
<button onclick="addRtl()">Add New Style Sheet</button>
<div class="title-bottom">.title-bottom</div>
</body>

替代方法:CSS属性

但是由于您将更改基于名为'dir'的属性,因此不需要任何JavaScript即可完成此操作。相反,您可以使用CSS [attribute=value] selector

CSS属性选择器的格式为[attribute=value],它将与将属性设置为该值的元素匹配。

要在document.dir === 'rtl'时进行样式修改,请使用:

[dir*=rtl] .title-bottom:before {
  left:initial;
}

展示如何使用CSS属性选择器的小例子:

function rtl() {
  document.dir = 'rtl';
}

function ltr() {
  document.dir = 'ltr';
}
[dir=rtl] p {
  color: red;
}
<h1>Change document.dir</h1>

<button onclick="rtl()">set rtl</button>
<button onclick="ltr()">set ltr</button>
<p>Paragraph text will be red when document.dir === 'rtl'</p>

相关问题