最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - How to use Javascript to add multiple style properties to one element? - Stack Overflow

programmeradmin0浏览0评论

I've tried various renditions of this code to try and change a certain element for a coding exercise but non of them seems to be able to change multiple styling properties of an element on a button click. Would love some assistance. Thanks!

document.getElementById("Combo Style").onclick = function() { document.getElementById ("More Text").style.fontSize.color = "50px , #BB65C5"; }

I've tried various renditions of this code to try and change a certain element for a coding exercise but non of them seems to be able to change multiple styling properties of an element on a button click. Would love some assistance. Thanks!

document.getElementById("Combo Style").onclick = function() { document.getElementById ("More Text").style.fontSize.color = "50px , #BB65C5"; }

Share Improve this question edited Jul 18, 2016 at 3:18 peterh 1 asked Jul 18, 2016 at 0:41 West Coast CharlieWest Coast Charlie 1031 gold badge2 silver badges9 bronze badges 1
  • 1 Possible duplicate of How to set multiple css style properties in Javascript – Sebastian Simon Commented Jul 18, 2016 at 0:43
Add a ment  | 

3 Answers 3

Reset to default 2

You can use cssText property but it will change the styling for the element pletely

Style cssText Property

document.getElementById("myP").style.cssText = "background-color:pink;font-size:55px;border:2px dashed green;color:white;"

This will overwrite the existing css styling for that element , so make sure you included every needed property.

To achieve your expected result use setAttribute
HTML:

<button id="Combo Style">Change</button>
<div id="More Text">abcd</div>

JS:

document.getElementById("Combo Style").onclick = function() {
  document.getElementById("More Text").setAttribute("style", "font-size:50px;color:red;");

}

http://codepen.io/nagasai/pen/AXVWwO

You need to grab the element by using id or any selector and use style property or css text property to apply css. Check the below code -

    var element=document.getElementById("More Text");
    element.style.fontSize="20px";
    element.style.color="red";
    element.style.background="blue";

You can also use cssText property, like -

document.getElementById("More Text").style.cssText='fontSize="20px";color="red";'

This will insert an inline style tag in the element with the csstext property.

发布评论

评论列表(0)

  1. 暂无评论