[英]CSS background color based on select value
Hopefully a simple question here. 希望这里有个简单的问题。 I have the following html code: 我有以下html代码:
<select id="dropdown">
<option value="#00FFFF">Cyan</option>
<option value="#FF00FF">Magenta</option>
</select>
<textarea style="background-color:[dropdown's selected value]">Sample Text</textarea>
What I'd like is the textarea's background color to dynamically change based on the dropdown's selection. 我想要的是textarea的背景颜色,可根据下拉菜单的选择动态更改。 Is there a simple way to reference the dropdown's value using CSS, or would JavaScript be the better route? 有没有一种简单的方法可以使用CSS引用下拉列表的值,还是JavaScript是更好的方法? HTML5 and CSS3 are definitely fair game here. HTML5和CSS3在这里绝对是公平的游戏。 Thanks! 谢谢!
You cannot do this just with HTML and CSS. 您不能仅使用HTML和CSS来执行此操作。 Some JavaScript is needed. 需要一些JavaScript。 Example: 例:
<select id="dropdown" onchange="setBg(this)">
<option selected value="#FFFFFF">White</option>
<option value="#00FFFF">Cyan</option>
<option value="#FF00FF">Magenta</option>
</select>
<textarea id="ta">Sample Text</textarea>
<script>
function setBg(sel) {
document.getElementById('ta').style.background =
sel.options[sel.selectedIndex].value;
}
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.