一.修改元素属性
例1:改变元素的属性
window.onload=function(){
var sxc=document.getElementById("sxc");
var llb=document.getElementById("llb");
var img=document.querySelector("img");
sxc.onclick=function(){
img.src="img/孙笑川.jpg"; //改变img的src
img.title="孙笑川"; //改变img的title
}
llb.onclick=function(){
img.src="img/李老八.jpg"
img.title="李老八";
}
}
<body>
<button id="sxc">孙笑川</button>
<button id="llb">李老八</button> <br>
<img src="img/孙笑川.jpg" alt="" title="孙笑川">
</body>
二.修改表单属性
例1:点击按钮,表单中的值改变
window.onload=function(){
var b=document.querySelector("button");
var i=document.querySelector("input");
b.onclick=function(){
i.value="打中辣!"
b.disabled=true; //点击一次后被禁用 等同于
//this.disabled=true; 当前按钮被禁用,指的是当前函数的调用者
}
}
<body>
<button>开炮</button>
<input type="text" value="">
</body>
</html>
例2:搜索框默认文字显示隐藏
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
input{
color: #999;
}
</style>
<script type="text/javascript">
/*
1.首先需要两个新事件:获得焦点onfocus 失去焦点onblur
2.若果获得焦点,判断表单里面的文字是否为默认文字,若是默认,就清空表单
*/
window.onload=function(){
var text=document.querySelector("input");
text.onfocus=function(){ //获得焦点事件
if(text.value==="请输入搜索内容"){ //如果表单内容为默认
text.value=""; //清空表单内容
}
text.style.color="#333"; //恢复文字颜色
}
text.onblur=function(){ //失去焦点事件
if(text.value===""){ //如果用户未输入内容,即表单为空
text.value="请输入搜索内容"; //表单恢复默认文字
}
text.style.color="#999"; //失去焦点文字变浅
}
}
</script>
</head>
<body>
<input type="text" value="请输入搜索内容">
</body>
</html>