普通修改
代码:
<script>
var btn=document.querySelector('button');
var img=document.querySelector('img')
btn.onclick=function(){
img.src='../images/2.jpg'
}
</script>
额外小知识:
this指的是事件源(对象)
js写的样式为行内样式。
使用className修改样式
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.div{
width: 100px;
height: 100px;
background-color: red;
}
.change{
width: 200px;
height: 200px;
background-color: rosybrown;
}
</style>
</head>
<body>
<div class="div"></div>
<script>
var div=document.querySelector('div');
div.onclick=function(){
div.className='change'
}
</script>
</body>
</html>
若想保留原先样式则可采用className='选择器1 选择器2’的方式。