<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>图片预览</title>
<script type="text/javascript">
//图片上传预览 IE是用了滤镜。
function previewImage(file) {
var div = document.getElementById('previmage');
var oldimg = div.firstChild;
var w = oldimg.style.width;
var h = oldimg.style.height;
// console.log(w + ',' + h);
if (file.files && file.files[0]) {
div.innerHTML = "";
var img = document.createElement("img");
img.style.width = w;
img.style.height = h;
div.appendChild(img);
img.src = window.URL.createObjectURL(file.files[0]);
} else //兼容IE
{
file.select();
file.blur();
var imgSrc = document.selection.createRange().text;
//必须设置初始大小
div.style.width = w;
div.style.height = h;
//图片异常的捕捉,防止用户修改后缀来伪造图片
div.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
div.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = imgSrc;
oldimg.style.display = "none";
document.selection.empty();
}
}
</script>
</head>
<body>
<p>By xxzkid</p>
<!-- 图片预览 -->
<div>
<input type="file" οnchange="previewImage(this);" />
<div id="previmage"><img src="" style="width: 200px; height: 200px;" /></div>
</div>
<!-- PS:#previmage > img 的width and height 一定要写在标签上,用class 或者id 选择器写的样式,在js中无法获取 -->
</body>
</html>
js实现图片预览
最新推荐文章于 2020-02-20 20:21:12 发布