使用 jQuery 更新 HTML 元素样式参数值

Update HTML element style parameter value using jQuery

本文关键字:样式 参数 元素 HTML jQuery 更新 使用      更新时间:2023-09-26

如何使用jQuery更新元素的style参数?

我有这个 HTML 代码:

<div id="template" style="width:200px; height:200px; border:none;">blabla...</div>

现在我尝试使用它:

$('#template').attr('style', '...');

而这个:

$('#template').prop('style', '...');

。但不起作用。

jQuery中有什么可行的解决方案吗?

更新

:我不想更新元素的样式。我只想直接覆盖stlye参数的值。

要更新现有样式,您可以使用 jquery .css()

$('#template').css('color', 'red');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="template" style="width:200px; height:200px; border:none;">blabla...</div>

jquery .attr() 向元素添加一个自定义属性。在您的 OP 中,它将使用新的更改属性style

$('#template').attr('style', 'color:red;border: solid 1px');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="template" style="width:200px; height:200px; border:1px solid;">blabla...</div>

如您所见,将仅保留新的。同样的方式可以在你的OP中工作.prop()。

.css()是使用 jQuery 操作样式的最佳方式。

文档

您的示例可以按如下方式完成:

$('#template').css({'font-size', '2em'});

你必须使用 jQuery css 方法,如果你想一次编辑多个属性,你需要尝试这样的事情:

$('#template').css({
   'font-size' : '10px',
   'width' : '30px',
   'height' : '10px'
});

而不是更新,覆盖!

忽略声明的内容,在运行时,jquery 将覆盖使用新值设置的内容。 因此,不要尝试以 style 属性为目标,只需重载它即可。

$('#template').css({'color': 'blue', 'width':'200px'});

你可以使用 jquery CSS API 来引用: http://api.jquery.com/css/

 $('#template').css('width', '100px'); // to change the width

或者,如果您有多个 CSS 样式属性要更改,请创建一个类并在那里声明所有样式,然后使用 jquery addClass API 引用:http://api.jquery.com/addclass/

 css:
  .someClass{ width:100px; opacity:0.5; color:blue}
 jquery:
   $('#template').addClass('someClass'); 

希望这有帮助

$(document).on('click', '#template', function() {
     $('#template').css({'color' : '#e8e8e8', 'width' : '25em'})
)};