How to pass the attribute value of a variable + string in the argument of .css () in jQuery

original code:

$bars[i].style.top =160 - height + sinTable[(ang + (i * freq)) & 4095] * height + "px";
$bars[i].style.height = height2 + "px";

but it seems that .style is rare, so I"m going to use .css instead:

var style={
    top:160 - height + sinTable[(ang + (i * freq)) & 4095] * height + "px",
    height:height2 + "px"
};
$bars[i].css(style);

in order to facilitate the direct passing of a variable (without quotation marks), a variable parameter is directly defined. But it didn"t have any effect. It is not possible to define variables separately.
wants to know how to pass in the parameter

if you want to use .css () to implement it.
Feb.26,2021

for DOM operation, it costs $bar [I] (point to DOM), but you want to use jq's css (), just $bars.css (style).


what was said upstairs is right.

in fact, jQuery applies the "shared meta-pattern" of the design pattern here, that is, using a set of shared data to reduce the memory and computational waste of a lot of repetitive content. So $('.bar') actually takes out all the DOM nodes, and then returns $bars not DOM Collection, but a jQuery instance, which is a class array object that contains many methods, such as .css (attr, value) .

so you should use $bars.css (style).

in addition, in theory, $bars [I] will return a DOM node. If you directly call the .css () method, you will report an error. It is recommended that you form the habit of "looking at the console first", which will be of great help in the future.


have you really taken a look at jQuery Api? no, no, no.
http://www.w3school.com.cn/jq.

$bars.css({
 top:...,
 height:...
})

by the way, style is used to write native JS directly when you don't use jQuery. There are four ways to write it:

$bars[i].style.height=...;//
$bars[i].style.cssText='height:...; top:...;';//
$bars[i].setAttribute('style', 'height:...;top:...');
$bars[i].style.setProperty('height', '...');

The last sentence of

is changed to:
$bars.eq (i) .css (style);

youdao is, "if you read a few documents, you will fall down when the wind blows."

Menu