简体   繁体   English

使用变量在jQuery中设置CSS属性值

[英]Using a variable to set css property value in jQuery

I want to set the height of a div based on the height of another div, which changes depending on the browser width. 我想根据另一个div的高度设置div的高度,该高度根据浏览器的宽度而变化。 I wrote the following which I think makes sense but it doesn't work, so I'm not sure if there's a way to do this or not? 我写了以下我认为有道理的文章,但没有用,所以我不确定是否有办法做到这一点?

$(window).on('resize', function() {

    var newHeight = $("#div1").height();
    $("div2").css(height, newHeight);

});

Thanks 谢谢

Your code have 2 issues 您的代码有2个问题

1) You need to write CSS property name in quotes. 1)您需要在引号中写CSS属性名称。

2) You are missing ID selector for div2 2)您缺少div2的ID选择器

$("#div2").css('height',newHeight);

You can set the height of an element using css : 您可以使用css设置元素的height

$("#div2").css('height', newHeight + 'px');
// ^           ^      ^            ^^^^^^^

You can also use height to set the height of an element. 您还可以使用height设置元素的高度。

$("#div2").height(newHeight);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM