简体   繁体   中英

How do you set the box-shadow CSS property with JavaScript?

i have some variable like this in JavaScript:

var classattrib = "box-shadow:inset 12px 222px 2px 2px rgba(1,2,111,11);";
target.style['boxShadow'] = classattrib;

or:

target.style['webkitBoxShadow'] = classattrib;

But it is not working

//html

<div id="target">hello</div>

What am I doing wrong?

Don't include the name of the property en the value, try like this:

var classattrib = "inset 12px 222px 2px 2px rgba(1,2,111,11)";
target.style.boxShadow = classattrib;

You could also use jQuery if it is an option.

Fiddle

HTML

<div id="textdiv">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Assumenda repellendus quam exercitationem ullam veniam ab reiciendis pariatur fuga quo id quisquam laudantium ducimus. Fugiat repellendus reprehenderit omnis qui odit unde. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nisi amet iste inventore quisquam in ut iure dolorum id cupiditate asperiores ullam facere eveniet recusandae harum nihil ex itaque. Possimus voluptatum!</p>
</div>

javaScript

$("#textdiv").css("box-shadow","inset 0px 0px 2px 2px rgba(1,2,111,11)");

If you want to assign the CSS declaration as a string, you should use cssText property as follows:

var classattrib = "box-shadow:inset 12px 222px 2px 2px rgba(1,2,111,11);";
target.style.cssText = classattrib;

Otherwise, you have to pass only the value of box-shadow property as:

var classattrib = "inset 12px 222px 2px 2px rgba(1,2,111,11)";
target.style.boxShadow = classattrib;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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