1 回答

TA貢獻1798條經(jīng)驗 獲得超7個贊
您正在尋求更改整個文檔的 CSS 規(guī)則。
執(zhí)行此操作的一種方法是將樣式表附加到文檔的 中,然后將規(guī)則更改放在那里。由于添加的樣式表是文檔中的最后一個樣式表,因此它將覆蓋默認規(guī)則。<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來實現(xiàn)此目的。相反,您可以使用 CSS [屬性 = 值] 選擇器。
CSS 屬性選擇器具有窗體 ,它將匹配將該屬性設(shè)置為該值的元素。[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>
添加回答
舉報