javascript实现上传图片并预览的效果实现代码


今天用alphaimageloader滤镜的src属就是其中的主角它将使用绝对或相对url地址指定背景图像。假如忽略此参数,滤镜将不会作用。
复制代码 代码如下:

<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html xmlns="http://www.3ppt.com /">
<head>
<meta http-equiv="content-type" content="text/html; charset=gb2312" />
<title></title>
<style type="text/css教程">
#picshow
{
filter:progid:dximagetransform.microsoft.alphaimageloader(sizingmethod=scale);
width:88px;
height:125px;
}
</style>
<script type="text/网页特效" language="javascript">
<!--
function upimg(imgfile)
{
var picshow = document.getelementbyid("picshow");
picshow.filters.item("dximagetransform.microsoft.alphaimageloader").src = imgfile.value;
picshow.style.width = "88px";
picshow.style.height = "125px";
}
-->
</script>
</head>
<body>
<div id="picshow"></div>
<p>选择图片:<input type="file" size="20" onchange="upimg(this);" /></p>
</body>
</html>

实例二、同时兼容ie6,ie7,ie8和 firefox。
复制代码 代码如下:

<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en"
"http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<script>
var picpath;
var image;
// preview picture
function preview()
{
document.getelementbyid('preview').style.display = 'none';
// 下面代码用来获得图片尺寸,这样才能在ie下正常显示图片
document.getelementbyid('box').innerhtml
= "<img width='"+image.width+"' height='"+image.height+"' id='apic' src='"+picpath+"'>";
}
// show view button
function buttonshow()
{
/*
这里用来解决图片加载延时造成的预览失败.
简单说明一下,当image对象的src属性发生改变时javascript会重新给image装载图片内容,
这通常是需要一些时间的,如果在加载完成之前想将图片显示出来就会造成错误,所以我们
通过图片的宽度和高度来判断图片是否已经被成功加载,加载完毕才会显示预览按钮.
这里我仍然有一个困惑,在ie7下预览效果偶尔会失效.
*/
if ( image.width == 0 || image.height == 0 ) {
settimeout(buttonshow, 1000);
} else {
document.getelementbyid('preview').style.display = 'block';
}
}
function loadimage(ele) {
picpath = getpath(ele);
image = new image();
image.src = picpath;
settimeout(buttonshow, 1000);
}
function getpath(obj)
{
if(obj)
{
//ie
if (window.navigator.useragent.indexof("msie")>=1)
{
obj.select();
// ie下取得图片的本地路径
return document.selection.createrange().text;
}
//firefox
else if(window.navigator.useragent.indexof("firefox")>=1)
{
if(obj.files)
{
// firefox下取得的是图片的数据
return obj.files.item(0).getasdataurl();
}
return obj.value;
}
return obj.value;
}
}
</script>
</head>
<body>
<input type="file" name="pic" id="pic" onchange='loadimage(this)' />
<input id='preview' type='button' value='preview' style='display:none;' onclick='preview();'>
<div id='box'></div>
</body>
</html>

« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3