javascript - 如何使用 jQuery 更改 CSS?

标签 javascript jquery css

我正在尝试使用 jQuery 更改 CSS:

$(init);
    
function init() {
    $("h1").css("backgroundColor", "yellow");
    $("#myParagraph").css({"backgroundColor":"black","color":"white");
    $(".bordered").css("border", "1px solid black");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="bordered">
    <h1>Header</h1>
    <p id="myParagraph">This is some paragraph text</p>
</div>

我在这里错过了什么?

最佳答案

忽略那些暗示属性名称是问题的人。 jQuery API 文档明确指出可以接受任何一种表示法:http://api.jquery.com/css/

实际问题是您在这一行中缺少右大括号:

$("#myParagraph").css({"backgroundColor":"black","color":"white");

改成这样:

$("#myParagraph").css({"backgroundColor": "black", "color": "white"});

这是一个工作演示:http://jsfiddle.net/YPYz8/

$(init);
    
function init() {
    $("h1").css("backgroundColor", "yellow");
    $("#myParagraph").css({ "backgroundColor": "black", "color": "white" });
    $(".bordered").css("border", "1px solid black");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="bordered">
    <h1>Header</h1>
    <p id="myParagraph">This is some paragraph text</p>
</div>

关于javascript - 如何使用 jQuery 更改 CSS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3730035/

相关文章:

javascript - 在 rails 中使用 jquery 显示工具提示

html - 带有子重叠 div 的 div 的内联显示

html - Fotorama 缩略图不显示 - 灰色 block ,点击时无图像

jquery - 我可以将 JQuery "this"与后代选择器一起使用吗?

html - 我可以在没有第二张图像的情况下在悬停期间更改 html 图像的外观吗?

javascript - 使用 javascript 更改 <a> 标记以使用所选选项值

javascript - 使用 jQuery 解析 XML

javascript - 在订阅时重复调用 Angular 中的 http

javascript - 由samplerCube引起的GL_INVALID_OPERATION

javascript - JS - 检测 UIwebView