1

我正在尝试将 css 属性添加到 Jquery 中的 css 变量中。

var cssProp = {
    'position': 'absolute',
    'top': topPos,
    'left': leftPos
}

//this codes works
cssProp.top += 10;

//this is not..
cssProp.z - index = 10;

如何解决这个问题?非常感谢!

4

5 回答 5

2

使用点表示法时,属性中不允许出现破折号

cssProp['z-index'] = 10;

请注意,在讨论element.styleCSS 中的所有虚线元素时,css 属性在 JavaScript 中都是驼峰式大小写的,因此它可能实际上是cssProp.zIndex = 10;

于 2012-09-07T20:22:59.257 回答
0

可能是因为 z-index 没有在 cssProp 中定义

尝试

var cssProp = {'position':'absolute',
                 'top': topPos,
                 'left': leftPos,
                 'z-index': 0
            }
于 2012-09-07T20:23:10.397 回答
0

以您的方式执行此操作正在创建一个名为“z-index”的新变量,该变量在 javascript 中无效,因此无法正常工作。

尝试将其称为“zIndex”,这是一个有效的 JavaScript 变量名。

于 2012-09-07T20:23:29.587 回答
0

使用-(破折号)作为变量名/对象键在 javascript 中无效。尝试使用 camelCase 表示法作为 zIndex。

阅读更多:

javascript变量名称中是否允许使用破折号?

于 2012-09-07T20:26:05.343 回答
0

像这样

var cssProp = {
    'position':'absolute',
    'top': topPos,
    'left': leftPos,
    'zIndex': '0'
};

jQuery always removes the '-' and then concatenates the word using the camelcase style type. I believe jQuery then has a regular expression that accomplishes this...

于 2012-09-07T20:27:39.457 回答