html代碼:
<form action="" method="post"> <img src="./demo_ui_1010/img/404.jpg" alt="" width="200" height="200"/ id="prevView"> <input type="file" name="" id="" value="" onchange="prev(this)"/> <input type="submit" value="上傳"/> </form>
css代碼:
<style type="text/css"> input[type="submit"]{ outline: none; border-radius: 5px; cursor: pointer; background-color: #31B0D5; border: none; width: 70px; height: 35px; font-size: 20px; } img{ border-radius: 50%; } form{ position: relative; width: 200px; height: 200px; } input[type="file"]{ position: absolute; left: 0; top: 0; height: 200px; opacity: 0; cursor: pointer; } </style>
JS代碼:
<script type="text/javascript">
function prev(event){
//獲取展示圖片的區域
var img = document.getElementById("prevView");
//獲取文件對象
let file = event.files[0];
//獲取文件閱讀器
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(){
//給img的src設置圖片url
img.setAttribute("src", this.result);
}
}
</script>
展示結果:

描述:
點擊圖片,會進入選擇圖片,選擇好圖片之后,圖片會變為已選擇的圖片。
總結:
1.點擊圖片域修改圖片。
form設置相對定位,input框設置相對定位,並且大小設置為和圖片一樣大小。
2.預覽實現原理。
利用HTML5的FileReader,有兼容性,低版本的瀏覽器支持性不好。
我是分割線------------------------------------------------------------------
