在 javascript 中更改样式属性使用 className

Changing the Style Attributes in javascript use className

本文关键字:属性 className 样式 javascript      更新时间:2023-09-26

HTML

<h1>Changing the Style</h1>
<p>JavaScript can change the style of an HTML element.</p>
<button type="button" onclick="openMe()">Open!</button>
<button type="button" onclick="closeMe()">Close!</button>
<p id="demo">Extra details...You can open and close this paragraph using the buttons above.</p>

.CSS

.close {
    display: none;
}
.open {
    display: block;
}
button {
    width:150px;
    background-color: #00CCEE;
    margin-left:15px;
    font-size:120%;
}
#demo {
    color:white;
    background-color: #7F7F7F;
    padding:10px;
    font-size:120%
}

JAVASCRIPT

function closeMe(){
    x=document.getElementById("demo");
    x.className="close";
}
function openMe(){
    x=document.getElementById("demo");
    x.className="open";
}

我可以在 Javascript 中使用 Like x.IdName= "close"; 吗?

到目前为止,我知道有两种方法可以使用Javascript更改样式属性。

x = document.getElementById("demo");
  1. 直接例如。( x.style.backgroundColor ="red" ;
  2. 按类名,例如。 ( x.className="abc";

    对于使用类名,我们使用:

    x = document.getElementById("demo");
    x.className="abc";
    

    我的问题:

我可以使用 Id 来更改样式属性而不是使用 className 吗? 如果是,请显示。

我可以调用"x"{x=document.getElementById("demo");}变量吗?

有三种方法可以使用 JavaScript 修改元素的样式:

  1. 修改内联样式。这由元素上的 .style 属性和 HTML 标记上的 style 属性表示。
  2. 修改元素的任何功能,以便样式表中规则集上的选择器开始和/或停止匹配它。 .foo { ... }将匹配属于 foo 类成员的元素,因此,如果修改 .className 属性以在该类中添加或删除元素,则将更改应用于该类的规则。您可以更改其他因素,例如id(通常不是逻辑概念)、任意属性或选择器存在的任何其他内容。
  3. 修改样式表本身中的规则集。

您已经修改了示例中元素的样式属性。

x.style.backgroundColor= "red";

这就是修改样式属性。第二个示例是编辑元素类名。我假设你的意思是你是否可以使用 id 将样式应用于元素?

如果是这种情况,您可以使用类选择器设置元素样式,如下所示

.className {
    /* Some styles */
}

或者使用 id 选择器

#demo {
    /* Other styles */
}

上面的两个示例要么需要进入它们自己的样式表中,要么需要在 <style></style> 元素的 HTML 中。

document.getElementById选择具有特定ID的元素。当您想通过类名选择元素时,您可以使用即 document.querySelector('.your-class')选择包含类名的节点。

当你写

x = document.getElementById("demo");
x.style.backgroundColor ="red"

您正在使用 Id 设置样式以选择节点。

在行中x = document.getElementById("demo"); x 是变量。运行此行后,此变量的值设置为document.getElementById("demo");返回的任何函数。在本例中,它指向具有 Id 属性"demo"的 DOM 元素。