js魅力所在應該就是它的靈活性很強,比如說當用了 元素.innerHTML=(所要內嵌的結構),加上事件和函數以后神奇的事就要發生了,原來的結構發生了變化,元素里又內嵌了一個結構。
說到內嵌呢,就不得不提一下字符串了。在拼接字符串的時候拼接字符串不管是單引號還是雙時引號在拼接的時候都會默認離自己最近的另一半是一對的,導致沒用好的話就把變量解析成字符串了。解決方法嘛~最靠譜的就是按老師說的,把填的結構先寫上,要從哪里加東西就在那里用兩個加號“劈開”然后再加內容 。
依靠這個我們做了簡易的聊天框,不過還不能進行線上聊天,只能 “ 自嗨 ” 一下,如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<style>
/*清除默認樣式*/
body{
margin:0;
background-color: mediumpurple;
}
dl,dd{
margin:0;
}
img{
border:none;
}
/* 設置樣式*/
#box{
position:relative;
width:320px;
height:563px;
padding:50px 15px 70px;
background: url(../img/bg.png) no-repeat;
margin:0 auto;/*為了看着方便將其顯示在屏幕中央*/
}
#bot{
position:absolute;
left:17px;
bottom:74px;
width:318px;
height:40px;
padding:10px 0;
background: rgba(0,0,0,.5);
}
#list{
padding-top:10px;
}
#list dl{
width:280px;
padding:10px 20px;
}
dl:after{
display: block;
content: "";
clear:both;
}
dd{
width:40px;
}
dt{
width:200px;
}
#list dt span{
font-size: 16px;
padding:5px 15px;
line-height: 30px;
background: #c35070;
color:#fff;
border-radius: 3px;
word-wrap:break-all;
}
#pic{
background: transparent;
border:none;
}
#inp{
vertical-align: top;
padding:0 15px;
border:none;
background-color: #fff;
border-radius: 3px;
width:160px;
height:40px;
font-size: 14px;
line-height: 40px;
}
#send{
vertical-align: top;
color:#e15671;
font-size: 14px;
background: transparent;
border:none;
line-height: 40px;
}
</style>
<body>
<!--布局-->
<div id="box">
<div id="list">
<!--<dl>
<dd>
<img src="" alt="" />
</dd>
<dt>
<span></span>
</dt>
</li>-->
</div>
<div id="bot">
<button id="pic">
<img src="../img/1.png" alt="" id="img"/>
</button>
<input type="text" id="inp" value=""/>
<button id="send">發送</button>
</div>
</div>
<!--用js將input里輸入的內容在dl里顯示-->
<script >
//聲明變量
var list = document.getElementById('list');
var inp = document.getElementById('inp');
var send = document.getElementById('send');
var img = document.getElementById('img');
var pic = 1//給圖片做標記
//點擊發送時,將輸入框中的內容展示在dl中
send.onclick = function(){
//判斷圖片序號從而決定是左浮動還是右浮動
if(pic == 1){
list.innerHTML = list.innerHTML+'<dl>'+"<dd style='float:left'>"+"<img src='../img/1.png'>"+'</dd>'+"<dt style='float:left'>"+"<span style='float:left'>"+inp.value+'</dt>'+'</span>'+'</dl>';
}else if ( pic == 2){
list.innerHTML = list.innerHTML+'<dl>'+"<dd style='float:right'>"+"<img src='../img/2.png'>"+'</dd>'+"<dt style='float:right'>"+"<span style='float:right'>"+inp.value+'</dt>'+'</span>'+'</dl>';
}
//發送成功后把輸入框內容清空
inp.value = "";
}
//通過判斷圖片序號判斷該切換哪張圖片
img.onclick = function () {
if (pic == 1){
img.src='../img/2.png';
pic = 2
}else if (pic == 2){
img.src='../img/1.png';
pic = 1
}
}
</script>
</body>
</html>
不過我寫的過於繁瑣,還有更簡單的,還沒整理出來,以后再補充 *✧⁺˚⁺ପ(๑・ω・)੭ु⁾⁾ 。
