定义file input
<div class="inputFileWrapper"> <label for="inputFile"> <input type="file" id="inputFile"/> <span class="custorm-style"> <span class="left-button">上传头像</span> <span class="right-text" id="rightText"></span> </span> </label> </div>
.inputFileWrapper label{ display: block; float: left; position: relative; } .inputFileWrapper input[type="file"]{ position: absolute; width: 1px; height: 1px; clip:rect(0,0,0,0); } .inputFileWrapper .custorm-style{ display: block; width: 390px; height: 50px; } .inputFileWrapper .custorm-style .left-button{ width: 80px; line-height: 50px; background: #008ac7; color: #fff; display: block; text-align: center; float: left; } .inputFileWrapper .custorm-style .right-text{ width: 300px; height: 40px; line-height: 50px; display: block; float: right; padding: 4px; border: 1px solid #008ac7; overflow: hidden; -ms-text-overflow: ellipsis; text-overflow: ellipsis; white-space: nowrap; }
<script src="js/jquery-1.11.1.min.js"></script> <script> var fileBtn = $("input[type=file]"); fileBtn.on("change", function(){ var index = $(this).val().lastIndexOf("\\"); var sFileName = $(this).val().substr((index+1)); $("#rightText").html(sFileName); }); </script>
示例:
自定义input file 的样式,
//.val()取的值是d:/userAdmin/uploads/20120515_115146.jpg; .lastIndexOf("\\")从零开始,最后一个\\的位置,所以下面要+1
//substr() 方法可在字符串中抽取从 start 下标开始的指定数目的字符,.substr(start,length)