gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 06:16:52 32 4
gpt4 key购买 nike

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(通常不是一个逻辑想法)、任意属性或selector 中的任何其他因素。存在于。
  3. 修改the rulesets in the stylesheet本身。

关于javascript - 在 javascript 中使用 className 更改样式属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35893083/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com