这一篇是基于上一篇:jQuery的$.ajax()与php后台交互,进行图片上传并删除,作的更新。
上一篇主要手动点击按钮进行上传和删除,那这一篇更新为在文本框进行使用键盘清除键将图片删除,并在服务器也一起删除。
ok,先看一波效果图,看是不是有点帮助。
好了,效果看完了,如果觉得有点意思的,那么接下来将讲怎么操作的。
1、我开始的想法是,先让文本框能够插入图片。但是发现<input type = "text">这个插入是不可能的事,然后我想到了<textarea></textarea>,但是很遗憾,他只会将“<img src =“”>”当作是字符串直接输出在文本框了,那好吧,google一下,突然StackOverflows上有人说可以用<div contentEditable="true"></div>就可以代替<textarea>了,哇,好样的,那在div里插入img简直易如反掌。
2、能够在文本框插入图片了,那怎么让他自动插入,没错jQuery的$(document).ready()事件,只需要在ready()里定义$("button").change()事件就可以自动识别你是否点击了“选择文件”按钮。如果不清楚change()事件,可以参考W3school:http://www.w3school.com.cn/jquery/event_change.asp
3、那好,插入图片没问题了,那怎么点击键盘清除键将图片删除呢?问题就来了,我以为div也有change()事件,那就好办了,点击清除返回img路径就可以啦,殊不知,div木有change()事件!!!那惨了,立了flag,没有也得有啊。我找啊找啊,突然又在StackOverflow找到有人说可以div.bind("DOMSubtreeModified", function())绑定一个事件DOM的子树改变事件就可以啦,哈哈哈,大胆试了一下,真可以,然后试完,要看完整文档来熟悉一下才行,直接MDN吧:MutationEvents(又名“突变事件”)
打开看到第一句话,咦?已废弃??!!!
可能我进入了假的StackOverflow,好吧,不过还好,看到那段黄色背景色的句子没有,原来MutationEvents更新成MutationObservers(又名“突变观察者”);
至于为什么MutationEvents会被废弃,大概的原因就是占用资源太严重,DOM4就把他给去掉了
详细情况:微软的MSDN这么说,而,一位简书的作者这么说。
我进入看了一下MutationObserver的文档,哇,简直懵逼,一时间还没搞懂怎么用的,又attribute,又childList什么的,蒙头转向,源码又特别少,后来琢磨了一下,大致是这样的。MDN官方文档代码如下:
<script type="text/javascript">
$(document).ready(function () {
// Firefox和Chrome早期版本中带有前缀
var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
// 选择目标节点
var target = document.querySelector('#id');
// 创建观察者对象
var observer = new MutationObserver(function(mutations){ //观察对象的回调函数
mutations.forEach(function(mutation) {
console.log(mutation.type);
}
// 配置观察选项:
var config = { attributes: true, childList: true, characterData: true ,subtree:true,characterDataOldValue:true};
// 传入目标节点和观察选项
observer.observe(target, config);
// // 随后,你还可以停止观察
// observer.disconnect();
}
</script>
那好,我想已经很清楚了,那接下来就要删除我的图片<img>了,如无意外,也是能够获取img的src就可以删除了。
还真行,
好了,贴上代码就可以收工
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<!--利用cdn添加js和css库 -->
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<style type="text/css">
#result{
text-align: center;
/* height: 400px;*/
width: 700px;
border: 1px solid red;
border-radius: 3px;
margin: 0 auto;
}
#result img{
margin:3px 10px;
border: 1px solid silver;
border-radius:50%;
padding: 6px;
width: 100px;
height:100px;
/* width: 35%;
height: 85%;*/
}
</style>
</head>
<body style="text-align: center; ">
<h1>结果</h1>
<div contentEditable="true" id="result">Type here. You can insert images too!</div>
选择图片:<input type="file" name="file" id="file" accept="image/gif,image/png,image/jpg,image/jpeg"><br>
<br><br><br><br>
</body>
<script type="text/javascript">
$(document).ready(function () { //jq的$(document).ready()相当于js的window.onload()事件
$("#file").change(function () { //change()事件,当元素id的值发生变化时
var formData = new FormData();
var file = document.getElementById('file').files[0]; //获取文件路径名,注意了没有files[1]这回事,已经试过坑
formData.append('file',file);
$.ajax({
type: "POST",
url: "server.php", //同目录下的php文件
data:formData,
// dataType:"json", //声明成功使用json数据类型回调
//如果传递的是FormData数据类型,那么下来的三个参数是必须的,否则会报错
cache:false, //默认是true,但是一般不做缓存
processData:false, //用于对data参数进行序列化处理,这里必须false;如果是true,就会将FormData转换为String类型
contentType:false, //一些文件上传http协议的关系,自行百度,如果上传的有文件,那么只能设置为false
success: function(msg){ //请求成功后的回调函数
$('#result').append(msg);
}
});
});
// $('#result').bind("DOMNodeInserted",function(){ //div标签不能使用直接使用change()事件,所以唯有用bind()来进行事件的绑定
// //console.log('changed');
// });
// Firefox和Chrome早期版本中带有前缀
var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
// 选择目标节点
var target = document.querySelector('#result');
// 创建观察者对象
var observer = new MutationObserver(function(mutations){ //观察对象的回调函数
console.log(mutations);
mutations.forEach(function(mutation) //forEach:遍历所有MutationRecord
{
console.log(mutation);
console.log(mutation.type); //MutationRecord.type
console.log(mutation.oldValue); // 注意mutation.type是childList,则不能使用oldValue来获取值
if(mutation.addedNodes[0]!=null){
console.log(mutation.addedNodes);
console.log(mutation.addedNodes[0]);
console.log(mutation.addedNodes[0].src);
if(mutation.addedNodes[0].tagName == "IMG")
console.log("成功添加一张img");
}
if(mutation.removedNodes[0]!=null)
{
console.log(mutation.removedNodes);
if(mutation.removedNodes[0].tagName == "IMG")
{
var href = location.href; //当前路径
console.log(href);
href = href.substring(0,href.lastIndexOf("/")+1);
console.log(href);
var imgSrc =mutation.removedNodes[0].src;
imgSrc = imgSrc.replace(href,''); //一种分离相对路径很笨的办法
$.ajax({
type: "POST",
url: "delete.php", //同目录下的php文件
data:{imgSrc,imgSrc},
success: function(msg){ alert(msg); } //请求成功后的回调函数
});
}
}
});
});
// 配置观察选项:
var config = { attributes: true, childList: true, characterData: true ,subtree:true};
// 传入目标节点和观察选项
observer.observe(target, config);
// // 随后,你还可以停止观察
// observer.disconnect();
})
</script>
</html>
server.php代码:
<?php
date_default_timezone_set('PRC'); //获取中国时区,'PRC':中华人民共和国
if(!file_exists(date("Ymd",time()))) //如果文件夹不存在,则创建一个
mkdir(date("Ymd",time()));
$filesName = $_FILES['file']['name']; //文件名数组
$filesTmpName = $_FILES['file']['tmp_name']; //临时文件名数组
$filePath = date("Ymd",time()).'/'.$filesName; //文件路径
if(!file_exists(date("Ymd",time()).'/'.$filesName)){
move_uploaded_file($filesTmpName, $filePath);
}
echo "<img src= '".$filePath ."'>";
?>
后台代码 delete.php 和上一篇是一样的:jQuery的$.ajax()与php后台交互,进行图片上传并删除