简体   繁体   中英

How to edit CSS hashtags using JavaScript

I have a page where i'm using both CSS and Javascript to edit values like:

document.getElementById("Doc1").style.opacity = "value";

However in this scenario, i can't seem to make it work because i can't get to #Image1

#Image1 =/= element.style

HTML,CSS Code

What i'm trying to do is change animation-play-state using the id = "Image1". Any solution?

When you edit the style of an element using the following:

document.getElementById("Doc1").style.opacity = "value";

You are setting the inline style of an element, not the styles applied by the #Image block.

If you'd like to edit the styles applied by the #Image block, there is some browser support for it using functions like insertRule() and deleteRule() .

Instead of editing the styles applied by a stylesheet, I would add or remove classes from elements.

<div id="my-div" class="is-running">test</div>

<style>
  .is-running { animation-play-state: running; }
  .is-paused { animation-play-state: paused; }
</style>

<script>
  document.getElementById('my-div').classList.remove("is-running");
  document.getElementById('my-div').classList.add("is-paused");
</script>

You can either remove the # from the string and use getElementByID or just use querySelector and pass the full ID.

id = id.replace("#","");

document.getElementById(id).style.opacity = "value";

or

document.querySelector("#Image1").style.opacity = "value";

If your issue is the animation-play-state part you can use this method:

document.getElementById(id).style["animation-play-state"] = "paused";

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