工作中遇到了需要将带有html标签的内容放进input框中显示,用户还可以进行修改,发现通过设置<input>
的value属性,不能将html元素进行转义显示,比如想让他显示 22 , 但是实际显示了 2<sup>2</sup>
,这显然不符合我们的要求。索性就把div伪装成一个input,这样就能通过$("#id").html(内容);的方式进行显示带有html标签的内容了。
下面贴上代码
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
.input{
width: 200px;
padding: 6px 12px;
font-size: 14px;
line-height: 1.42857143;
color: #555;
background-color: #fff;
background-image: none;
border: 1px solid #ccc;
border-radius: 4px;
outline: none;
overflow: hidden;
white-space: nowrap;
display: block;
-webkit-transition: border-color ease-in-out .15s, -webkit-box-shadow ease-in-out .15s;
-o-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
}
.input:empty::before{
color:#ADADAD;
content:attr(placeholder);
font-size: 14px;
}
.input:focus{
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
}
</style>
</head>
<body>
<div id="title" name="title" class="input" contenteditable placeholder="请输入内容" onkeydown="myFunction()"></div>
</body>
<script type="text/javascript">
function myFunction(){
if (window.event && window.event.keyCode == 13) {
window.event.returnValue = false;
}
}
</script>
</html>
实现方法是利用 contenteditable 将div设置为可编辑,然后调整div样式,此样式借鉴了Bootstrap的input框样式。
默认文字通过伪元素来根据placeholder显示。
input:focus类的作用是div获取焦点之后为其添加阴影。
myFunction()的作用是禁止用户使用回车换行。