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

标签 javascript html css

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/

相关文章:

javascript - 我什么时候应该在独立的 node.js 上使用 express.js

javascript - 如何计算luxon中两个日期之间的持续时间?

javascript - 将语音响应添加到 HTML 页面

html - 为什么右侧超出浏览器大小?

javascript - 单击“选择”选项时如何更改箭头方向

javascript - 在 codeigniter 中以时间戳格式搜索查询

android - 如何在android中合并音频和视频文件

javascript - 模板在正确加载之前中断

html - 在 Mac 版 Chrome 中丢失悬停样式

javascript - 将 infoBox 替换为 jquery 对话框模式窗口