简体   繁体   English

使用jQuery将自定义样式字符串应用于div

[英]apply custom style string to div using jquery

I have a javascript variable with the following value: 我有一个具有以下值的javascript变量:

var style ="border-left:12px solid;border-color:red;position:relative;"

How can I apply it to a div like below: 我如何将其应用于如下所示的div:

<div class='my-div'></div>

I tried: 我试过了:

$('.my-div').css({style});

but failed spectacularly :( 但是失败了:(

var style = {
    borderLeft:'12px solid',
    borderColor:'red',
    position:'relative'
}

The object should look like this. 该对象应如下所示。 The CSS method takes in an object param. CSS方法接受对象参数。 Doing a style string concat will work, but it's ugly. 进行样式字符串concat可以工作,但这很丑。

Or use a class and be simple. 或使用一个类并且简单。

$('.my-div').css(style); //append style object to jQuery object

Note that using this object notation can also be beneficial because the properties can have logic in them, say for animations, or changing value dependencies. 请注意,使用此对象表示法也可能是有益的,因为属性可以在其中包含逻辑,例如用于动画或更改值依赖性。

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

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