目录
- select + option
- innerHTML 在元素中插入内容
select + option
可以实现一个下拉选择,选择到那个,就可以获取其value,并且弹窗。
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<style>
.sty1{background-color:#aaa;height:200px;width:200px;margin-top:20px;float:left;margin-left:10px;}
</style>
</head>
<body>
<div id = "div1" class = "sty1" ></div>
<div id = "div2" class = "sty1"></div>
<div id = "div3" class = "sty1" ></div>
<select id = "s1" onchange = "m1()">
<option value="flag0">请选择样式</option>
<option value="flag1">样式1</option>
<option value="flag2">样式2</option>
<option value="flag3">样式3</option>
<option value="flag4">样式4</option>
<option value="flag5">样式5</option>
<select>
</body>
<script>
function m1(){
var x = document.getElementById("s1");
alert(x.value);
}
function m2(){
}
</script>
</html>
这样我们就可以根据获取到的不同value,做出不同的动作如:
function m1(){
var x = document.getElementById("s1");
var x1 = document.getElementById("div1");
var x2 = document.getElementById("div2");
var x3 = document.getElementById("div3");
alert(x.value);
if (x.value == "flag1"){
x1.style.backgroundColor = "#a00";
}else if (x.value == "flag2"){
x2.style.width = "300px";
}else if (x.value == "flag3"){
x3.style.opacity = "0.5";
}
}
innerHTML 在元素中插入内容
注意: 最好用单引号’来表示,以防和其中的"冲突,当然也可用\掉",但是太麻烦了。
如:
var x1 = document.getElementById("div1");
if (x.value == "flag1"){
x1.innerHTML = "大家好";
当我们选择标签1的时候在div1中插入文字"大家好"
当然不止可以放文本,还可以放入其他元素比如我们这里放入几个小方块嵌套在其中。
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<style>
.sty1{background-color:#aaa;height:200px;width:200px;margin-top:20px;float:left;margin-left:10px;}
</style>
</head>
<body>
<div id = "div1" class = "sty1" ></div>
<div id = "div2" class = "sty1"></div>
<div id = "div3" class = "sty1" ></div>
<select id = "s1" onchange = "m1()">
<option value="flag0">请选择样式</option>
<option value="flag1">样式1</option>
<option value="flag2">样式2</option>
<option value="flag3">样式3</option>
<option value="flag4">样式4</option>
<option value="flag5">样式5</option>
<select>
</body>
<script>
function m1(){
var x = document.getElementById("s1");
var b1 = document.getElementById("div1");
var x2 = document.getElementById("div2");
var x3 = document.getElementById("div3");
//alert(x.value);
if (x.value == "flag1"){
b1.backgroundColor = "#2ac";
var html = ' ';
for (var i = 0; i < 10; i++){
html += '<div style = "height:40px;width:40px;background-color:#2ac;float:left;margin-left:10px;margin-top:10px;"></div>';
}
b1.innerHTML = html;
}
}
function m2(){
}
</script>
</html>