如何用JS改变CSS类的样式

问题描述 投票:0回答:1

我有一个css clas是这样的,left:0将下划线设置为左,但当RTL激活时,它必须向右浮动。

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

左:0将下划线设置为左,但当RTL激活时,它必须是浮动的右。所以,我想把左:0改为左:初始化,如果rtl存在的话。

我怎么做呢?我开始写这样的代码。

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

但我无法继续写下去了. 因为我找不到好的JS学习资源.

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

javascript
1个回答
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 Attributes

但由于你是基于一个叫做'dir'的属性进行修改,所以你不需要任何JavaScript来完成这个任务。相反,你可以使用 CSS [attribute=value] 选择器.

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>
© www.soinside.com 2019 - 2024. All rights reserved.