You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用jQuery的attr()定义多个CSS属性,为何margin-top设置失效

问题原因

  • jQuery的attr()方法设置单个属性时仅接受两个参数:attr(属性名, 属性值),你合并写法中传入的第三个参数'margin-top:xxx'会被直接忽略,因此只有第一个margin-left样式生效。
  • style是元素的单个属性,它的取值是包含所有样式规则的完整字符串,多个样式规则需要用分号;分隔,不能拆分为多个参数传递给attr()。

额外提示:你拆分两次调用attr('style')的写法逻辑上是错误的,第二次调用会直接覆盖第一次设置的全部style属性值,最终只会保留margin-top的设置,你观察到的“正常运行”属于测试场景的特殊巧合,不要在生产环境使用该写法。

正确实现方式

方案1:拼接完整style字符串(使用attr实现)

将两个样式规则拼到同一个字符串中,用分号分隔:

var hoeheDrBoxPA = (jQuery(".header-a-p").outerHeight()/2);
var hoeheDrBoxHPA = (jQuery(".text-h-a-p").outerHeight()/2);
var hoeheDrBoxPAML = (jQuery(".header-a-p").css("marginLeft"));
            
jQuery(".et_pb_section_1.header-element").attr('style', 'margin-left:' + hoeheDrBoxPAML + '!important;margin-top:' + (hoeheDrBoxPA-hoeheDrBoxHPA) + 'px');

方案2:更推荐使用jQuery原生css()方法设置样式

操作元素样式优先使用css()方法,支持直接传入对象同时设置多个样式,无需手动拼接字符串,兼容性更强:

var hoeheDrBoxPA = (jQuery(".header-a-p").outerHeight()/2);
var hoeheDrBoxHPA = (jQuery(".text-h-a-p").outerHeight()/2);
var hoeheDrBoxPAML = (jQuery(".header-a-p").css("marginLeft"));

jQuery(".et_pb_section_1.header-element").css({
  'margin-left': hoeheDrBoxPAML + '!important',
  'margin-top': (hoeheDrBoxPA - hoeheDrBoxHPA) + 'px'
});

内容的提问来源于stack exchange,提问作者Martin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 23:45:05