最近項目中有個詳細預覽功能,詳細中的某個字段存放的是完整的html,在頁面中須要正常展現。html
那麼問題來了:app
一、須要展現的html中的樣式會與外面的頁面衝突。測試
二、直接加載數據中的html,可能存着一些腳本錯誤。this
首先想到的解決辦法是用iframe,可是iframe是直接加載某個頁面。因此須要動態的添加html內容到iframe中。spa
$('<p><iframe id="myFrame" src="crawler_data_iframe.html" width="500px" height="200px;" ></iframe></p>').appendTo($(div)); var o = document.getElementById("myFrame"); ed = document.all ? o.contentWindow.document : o.contentDocument; ed.open(); ed.write(data); ed.close(); ed.contentEditable = true; ed.designMode = 'on';
經測試能正常顯示html的內容。然而發現iframe中的html點擊相關元素會發生頁面跳轉等相關事件,須要取消點擊觸發的原始事件。添加以下代碼:code
$(this).click(function (event) { event.preventDefault(); })
經測試,沒有效果。因而想起能夠經過樣式取消點擊效果。htm
<style> iframe{ pointer-events: none; } </style>
可是這樣iframe的滾動條也不能點擊了,因而想起樣式能夠加在文檔裏面,修改代碼以下:blog
$('<p><iframe id="myFrame" src="crawler_data_iframe.html" width="500px" height="200px;" ></iframe></p>').appendTo($(div)); var o = document.getElementById("myFrame"); ed = document.all ? o.contentWindow.document : o.contentDocument; ed.open(); ed.write(` <!DOCTYPE html> <html lang="en"> <head> <title></title> <meta charset="UTF-8"> <style> #data_id{ pointer-events: none; } </style> </head> <body> <div id="data_id">${data}</div> </body> </html>`); ed.close(); ed.contentEditable = true; ed.designMode = 'on';
經測試,iframe中的html不能點擊,預期的取消了點擊事件的效果。事件