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="" ?/></dd><dt><span></span></dt></li>--></div><div id="bot"><button id="pic"><img src="../img/1.png" ?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>
不过我写的过于繁琐,还有更简单的,还没整理出来,以后再补充 *?????(??ω?)???? 。
js ?- 运用内嵌来实现动态布局
原文地址:https://www.cnblogs.com/zyuu/p/8205318.html