昨天在项目中遇到一个关于js动态创建一个<a href="资源地址" />然后append到<body>标签上显示的问题,发现添加到<body>标签上无法显示,代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>展示图片</title>
<style>
.dialog {
position: fixed;
width: 700px;
height: 700px;
left: 50%;
margin-left: -350px;
top: 100px;
border: 0px solid rgb(70, 233, 253);
background-color: rgba(78, 108, 140, 0.66);
z-index: 20;
}
.dialog-head {
height: 40px;
width: 100%;
border-bottom: 1px white dotted;
opacity: 1;
}
.close-btn {
float: right;
line-height: 40px;
cursor: pointer;
margin-right: 12px;
color: white;
}
.dialog-content {
width: 100%;
height: 100%;
}
.dialog-img {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
显示图片
</body>
<input type ='button' value='预览' οnclick='preview("完整的url地址")'>
<script src="jquery.min.js"></script>
<script>
function preview(addr){
var dlgStr = '<div class="dialog"><div class="dialog-head"><div class="close-btn" οnclick="closeDlg()">关闭</div></div><div class="dialog-content"><a href="'
+ addr + '" class="dialog-img"/></div></div>';
$('body').append(dlgStr);
}
function closeDlg(){
$(".dialog").remove();
}
</script>
</html>
上面这样的代码,当点击预览按钮的时候,发现并没有像我想像的那样页面弹出对话框并显示内容,原因是append的是一段静态的代码,并没有事件触发去执行这个代码,所以无法显示我们想要显示的资源文件。
经过对上面问题现象的分析,我们可以使用jquery的media插件来解决这个问题,这个插件可以在线预览一些文档个是的资源文件,例如:pdf,word等比较常用的文件格式资源。
下面是改进后的代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>展示图片</title>
<style>
.dialog {
position: fixed;
width: 700px;
height: 700px;
left: 50%;
margin-left: -350px;
top: 100px;
border: 0px solid rgb(70, 233, 253);
background-color: rgba(78, 108, 140, 0.66);
z-index: 20;
}
.dialog-head {
height: 40px;
width: 100%;
border-bottom: 1px white dotted;
opacity: 1;
}
.close-btn {
float: right;
line-height: 40px;
cursor: pointer;
margin-right: 12px;
color: white;
}
.dialog-content {
width: 100%;
height: 100%;
}
.dialog-img {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
显示图片
</body>
<input type ='button' value='预览' οnclick='preview("http://www.cnblogs.com/tangzhengyue/p/4315393.html")'>
<script src="jquery.min.js"></script>
<script src="jquery.media.js"></script>
<script>
function preview(addr){
//carImg.closeDlg();
var dlgStr = '<div class="dialog"><div class="dialog-head"><div class="close-btn" οnclick="closeDlg()">关闭</div></div><div class="dialog-content"><a href="'
+ addr + '" class="dialog-img"/></div></div>';
$('body').append(dlgStr)
$('.dialog-img').media({
width : 700,
height : 700
});
}
function closeDlg(){
$(".dialog").remove();
}
</script>
</html>
上面的代买可以完美的解决资源文件在页面动态显示问题。
完整的demo示例地址: http://download.youkuaiyun.com/detail/zhengyangzkr/9822029