【问题标题】:Setting opacity value of a button with javascript使用javascript设置按钮的不透明度值
【发布时间】:2013-08-31 22:08:30
【问题描述】:

我正在尝试设置一个按钮,以便每次用户单击它时,它的不透明度都会上升,直到达到 1。我明白了,但这仅适用于第一次单击。下一次点击已注册,但不会增加不透明度。

document.getElementById('buttonHello').style.opacity+=0.1;

谢谢

编辑:你好,我需要帮助。

【问题讨论】:

  • 没关系,我使用了另一种方法,但我仍然很好奇,不透明度是字符串还是什么?
  • alert(typeof document.getElementById('buttonHello').style.opacity) 会回答这个问题。
  • 你需要使用window.getComputedStyle(element).getPropertyValue(prop)

标签: javascript css opacity


【解决方案1】:

执行此操作演示 http://jsfiddle.net/techsin/A7eMh/

function ch() {
var x=getComputedStyle(document.getElementById('buttonHello')).getPropertyValue('opacity');
x=(x*1)+.1;
document.getElementById('buttonHello').style.opacity=x;
}

【讨论】:

    【解决方案2】:

    我做了一支笔来说明如何做到这一点(在达到 1 后将不透明度恢复为 0.1):

    http://codepen.io/MisterGrumpyPants/pen/Gofhd

    关键是这个 JS:

    var button = document.getElementById('buttonHello');
    
    var getOpacity = function(el) {
      return el.style.opacity;
    }
    
    button.addEventListener('click', function() {
      var currentOpacity = parseFloat(getOpacity(button));
      var newOpacity = (currentOpacity < 0.9) ? currentOpacity + 0.1 : 0.1;
      button.style.opacity = newOpacity;
    });
    

    也许您需要了解的是parseFloat() 部分?

    更新:getComputedStyle 还是 element.style?

    如果您需要从样式表中获取 opacity 值,而不是内联样式,我认为您会使用 getComputedStyle(请注意,我从 codepen 中的内联值开始)。但是一旦你用 JS 设置了内联样式,我想你还不如使用element.style.opacity。 (其实我也碰到过这个jsPerf test suggesting that .style is significantly faster than getComputedStyle。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-05
      • 1970-01-01
      • 1970-01-01
      • 2012-02-09
      • 2018-06-30
      • 2015-09-20
      • 1970-01-01
      • 2019-03-18
      相关资源
      最近更新 更多