這一篇是基於上一篇: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後臺交互,進行圖片上傳並刪除
jQuery的$.ajax()與php後臺交互,利用MutationObserver進行圖片刪除
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.