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

javascript - How do I set opacity of an element using JS? - Stack Overflow

programmeradmin3浏览0评论

I know how to set it in a style sheet. This explains how to get it using JS...

I tried this to set it:

window.getComputedStyle( myEl ).setPropertyValue( 'opacity', 0.7 );

and got

setPropertyValue is not a function.

Obviously I can use JQuery css( ... )... in the min.js file I found there were no fewer than 10 matches for opacity. I didn't have a clue about what was going on.

This is Firefox, by the way.

I know how to set it in a style sheet. This explains how to get it using JS...

I tried this to set it:

window.getComputedStyle( myEl ).setPropertyValue( 'opacity', 0.7 );

and got

setPropertyValue is not a function.

Obviously I can use JQuery css( ... )... in the min.js file I found there were no fewer than 10 matches for opacity. I didn't have a clue about what was going on.

This is Firefox, by the way.

Share Improve this question edited Sep 27, 2017 at 18:59 P.S. 16.4k14 gold badges65 silver badges86 bronze badges asked Sep 27, 2017 at 18:45 mike rodentmike rodent 15.8k14 gold badges120 silver badges195 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

By modifying the style property.

myEl.style.opacity = 0.7;

Here is the live example for opacity change:

var target = document.getElementById('target');
var currentOpacity = window.getComputedStyle(target).opacity;

function decreaseOpacity() {
  if (currentOpacity > 0) {
    target.style.opacity = currentOpacity - 0.1;
    currentOpacity -= 0.1;
  }
}

function increaseOpacity() {
  if (currentOpacity < 1) {
    target.style.opacity = currentOpacity - 0.1;
    currentOpacity += 0.1;
  }
}
#target {
  width: 100px;
  height: 100px;
  background-color: violet;
  opacity: 1;
}
<div id="target"></div>
<button onclick="decreaseOpacity()">Decrease opacity</button>
<button onclick="increaseOpacity()">Increase opacity</button>

发布评论

评论列表(0)

  1. 暂无评论