2017-01-09 78 views
0

我希望用户可以通过点击ON(不透明度100%)或OFF(不透明度0%)而不是1或0来改变不透明度。这可能吗? 代码:使用javascript,如何更改不透明度ON和OFF?

<!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> 
+0

只是值设为您的选项=“”,然后设置该选定值的不透明度。然后你可以用任何你想要的文字来标记它们。 – vico

+0

谢谢!我感谢您的帮助! – BlecKent

回答

2

如果你可以改变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>

+0

谢谢!有用。这很容易,我还不是专家,我还在学习。谢谢! – BlecKent