gpt4 book ai didi

javascript - 在 jQuery 中使用变量作为 .css() 样式属性

转载 作者:太空宇宙 更新时间:2023-11-03 18:10:46 24 4
gpt4 key购买 nike

我正在尝试通过 jQuery 创建一个响应式设计,它将根据特定的页面宽度调整各种 css 样式属性的值。不幸的是,当我尝试将变量传递给样式属性的 .css() 时遇到了麻烦。

相关代码如下:

if (screenWidth < maxWidth && screenWidth > minWidth) {
container.css({stylePropToChange: (minValue + widthPercent) + unit});
//the problem area is here^^^
} else if (screenWidth >= maxWidth) {
container.css({stylePropToChange: minValue + unit});
} else {
container.css({stylePropToChange: maxValue + unit});
}

Full code: jsfiddle

在此代码中,stylePropToChange 变量未被识别为“宽度”。如果我只用字符串“width”替换它,就像这样:

container.css({"width": (minValue + widthPercent) + unit});

...现在可以使用了。为什么 jQuery 不接受 .css() 的“属性名称”端的变量,但接受值端的变量?

我该怎么做才能使这项工作成功?

在寻找答案时,我找到了 this question posted in the jquery forums ,有人遇到了不同的问题,但他们以某种方式能够做我想做的事情。我只是错过了一些简单的东西吗?

最佳答案

您不能以这种方式设置 javascript 对象属性。只需使用:

container.css(stylePropToChange, minValue + unit);

等如果你想继续这样做。顺便说一句,我真的不明白为什么你不在你的 css 中使用多个 @media 查询来做同样的事情。你能解释一下为什么你想用 javascript 来做吗?

关于javascript - 在 jQuery 中使用变量作为 .css() 样式属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23772843/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com