javascript - 使用 javascript,如何通过 ON 和 OFF 更改不透明度?

标签 javascript html css

我希望用户可以通过点击打开(不透明度 100%)或关闭(不透明度 0%)而不是 1 或 0 来更改不透明度。这可能吗? 代码:

<!DOCTYPE html>
<html>
<body>

<p id="p1">Change this phrase's opacity</p>   

<select onchange="myFunction(this);" size="2">
<option>0  <!--I want this OFF not 0-->
<option selected="selected">1 <!--I want this ON not 1-->
</select>

<script>
function myFunction(x) {
   var opacity = x.options[x.selectedIndex].text;
   var el = document.getElementById("p1");
   if (el.style.opacity !== undefined) {
      el.style.opacity = opacity;
    } else {
        alert("Your browser doesn't support this!");
    }
}
</script>

</body>
</html>

最佳答案

如果您可以将选项更改为具有值,您可以执行以下操作:

function myFunction(x) {
  var opacity = x.options[x.selectedIndex].value;
  var el = document.getElementById("p1");
  if (el.style.opacity !== undefined) {
    el.style.opacity = opacity;
  } else {
    alert("Your browser doesn't support this!");
  }
}
<p id="p1">Change this phrase's opacity</p>

<select onchange="myFunction(this);" size="2">
  <option value="0">OFF</option>
  <option value="1" selected="selected">ON</option>
</select>

关于javascript - 使用 javascript,如何通过 ON 和 OFF 更改不透明度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41551980/

相关文章:

javascript - 如果元素被 css 隐藏,则 MouseEvent 被吞下

javascript - 重新渲染 View 时如何控制文本字段焦点?

javascript - jQuery/HTML - 在使用等宽字体时,如何使空格 ( ) 占用与另一个字符相同的空间量?

javascript - 如何在 Solidity 中构建 HTML 解决方案

html - 奇怪的 IE 错误 - Wordpress 主题

css - Angular 没有完全加载样式

html - CSS - 联系表单动画

javascript - 无法在 Tizen 可穿戴 Web 应用程序中显示 OpenStreepMap

html - 将 bash 脚本的结果插入到 html 表中

javascript - margin-left 和 width 属性在 mozilla firefox 中不起作用