2

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"; }

4

3 回答 3

0

要实现您的预​​期结果,请使用 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

于 2016-07-18T00:48:00.927 回答
0

您可以使用 cssText 属性,但它会完全改变元素的样式

样式 cssText 属性

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

这将覆盖该元素的现有 css 样式,因此请确保包含所有需要的属性。

于 2021-04-03T10:36:13.650 回答
-2

您需要使用 id 或任何选择器来抓取元素,并使用 style 属性或 css 文本属性来应用 css。检查下面的代码 -

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

您还可以使用 cssText 属性,例如 -

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

这将在具有 csstext 属性的元素中插入一个内联样式标记。

于 2016-07-18T06:25:31.210 回答