使用 javascript,我怎样才能用 ON 和 OFF 来改变不透明度



我希望用户可以通过单击ON(不透明度100%)或OFF(不透明度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>
如果

可以将options更改为具有值,则可以执行以下操作:

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>

最新更新