<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
#phone {
width: 350px;
height: 600px;
margin: 0 auto;
background: url(phone.jpg) no-repeat;
background-size: 350px 600px;
position: relative;
}
#interface {
position: absolute;
width: 290px;
height: 390px;
background-color: white;
top: 85px;
left: 30px;
}
#chat {
position: absolute;
height: 40px;
width: 290px;
bottom: 88px;
left: 30px;
background-color: #EBF8F6;
}
#portoait {
position: absolute;
width: 30px;
height: 30px;
border: 1px solid black;
top: 5px;
}
#container {
position: absolute;
width: 180px;
height: 25px;
left: 35px;
top: 5px;
}
#submit {
position: absolute;
height: 35px;
width: 60px;
right: 5px;
top: 5px;
border: 0;
background-color: transparent;
}
.one{
width: 100%;
height: 20px;
float: left;
}
.left{
background-color: skyblue;
padding: 5px;
}
.right{
background-color: yellowgreen;
padding: 5px;
}
.two img,
.right{
float: right;
}
</style>
</head>
<body>
<div id="phone">
<div id="interface">
</div>
<div id="chat">
<img src="1.png" id="img" />
<input type="text" id="container" />
<button id="submit">发送</button>
</div>
</div>
<script type="text/javascript">
var phone = document.getElementById("phone")
var interface = document.getElementById("interface")
var img = document.getElementById("img")
var container = document.getElementById("container")
var submit = document.getElementById("submit")
//头像变换
var flag = true;
img.onclick = function() {
if(flag == true) {
img.src = "2.png"
flag = false;
} else {
img.src = "1.png"
flag = true;
}
}
submit.onclick = function() {
if(flag == true) {
interface.innerHTML += "<p class='one'><img src='1.png' />" + "<span class='left'>"+container.value+"</span>"+"</p>"
} else {
interface.innerHTML += "<p class='two'> <img src = '2.png'>" + "<span class ='right'>"+container.value+"</span>"+"</p>"
}
container.value=""
}
</script>
</body>
</html>
效果:
思路:在布局好之后,首先对于头像切换问题使用 flag=true 判断点击事件,在点击事件结束后将false赋值给flag进行下一次判断,否则会进入死循环 也可以用数字判断,不过要处理好逻辑,不然接下来的内容不太好写。
对于输出内容,主要是用innerHTML拼接头像信息和具体内容输出内容用value获取。记得加标签,不然两个头像会在一列显示。标签尽量使用规范,代码中用了<p><img/></p>不建议使用。
对于点击事件,只是初次使用,在以后会逐渐完善