一、效果展示
二、代码实现
<!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>百度搜索</title>
</head>
<body>
<div id="box1" class="box1">
<div class="image"><img src="../asset/bd_logo.jpeg" alt=""></div>
<input type="text"><button>百度一下</button>
</div>
</body>
<script>
var box1 = document.getElementById("box1")
var input = document.querySelector("input")
input.onkeyup = function() {
box1.setAttribute('class', 'box2')
}
</script>
<style>
/* 初始化全局样式 */
* {
margin: 0;
padding: 0;
}
.box1 {
width: 600px;
height: 300px;
margin: 250px auto;
position: relative;
}
.box2 {
width: 600px;
height: 300px;
margin: 0 0 0 180px;
position: relative;
padding-top: 40px;
}
.box1 input {
width: 500px;
height: 40px;
box-sizing: border-box;
text-indent: 10px;
font-size: 16px;
}
.box2 input {
width: 500px;
height: 40px;
box-sizing: border-box;
text-indent: 10px;
font-size: 16px;
}
button {
width: 100px;
height: 40px;
box-sizing: border-box;
background-color: #38f;
border: none;
color: white;
font-size: 16px;
position: absolute;
left: 500px;
/*聚焦样式 */
cursor: pointer;
border-radius: 3px;
}
button:hover {
background-color: #2d78f4;
}
.box1 .image {
position: absolute;
top: -140px;
left: 170px;
}
.box1 .image img {
width: 270px;
height: 130px;
}
.box2 .image {
position: absolute;
top: 18px;
left: -170px;
}
.box2 .image img {
width: 170px;
height: 80px;
}
</style>
</html>
三、涉及要点
1.动态为页面元素添加类
var box1 = document.getElementById("box1")
var input = document.querySelector("input")
input.onkeyup = function() {
box1.setAttribute('class', 'box2')
}
注意:
- 获取元素不能通过class来获取,否则在setAttribute的时候会报错
- input是输入框,onkeyup是在输入框输入内容时按键抬起时触发