通過 github 搜索 object-fit ie , 借鑒大佬兼容 ie 的經驗。
下載解壓到文件夾 , 打開測試目錄 , 查看 demo
使用 ie 打開demo , 查看顯示效果 :
代碼 :
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <link rel="stylesheet" href="styles.css"> <link rel="stylesheet" href="../dist/polyfill.object-fit.css"> <style> img { width: 100%; height: 35em; margin: 10px 0; border: 5px solid red; object-fit: cover; overflow: hidden; } </style> </head> <body> <h1><code>object-fit: cover;</code></h1> <img src="image.jpg"> <script src="../dist/polyfill.object-fit.js"></script> <script> // Call polyfill to fit in images document.addEventListener('DOMContentLoaded', function () { objectFit.polyfill({ selector: 'img', fittype: 'cover' }); }); </script> </body> </html>
通過 demo 可以發現 需要引入的文件 :polyfill.object-fit.css 和 dist/polyfill.object-fit.js 。
還需要 底部初始化 , 在 fittype 后 輸入 object-fit 的類型。 即可實現對 ie 的兼容
以下是我個人的實踐 :
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="./polyfill.object-fit.min.css"> <title>響應式圖片</title> <style> body{ margin: 0; } img{ height: 100vh; width: 100%; display: block; object-fit: cover; } </style> </head> <body> <picture> <!-- 橫屏 320px--> <source media="(min-width: 320px) and (max-width: 640px) and (orientation: landscape)" srcset="./img/lx.png"> <!-- 豎屏 320px--> <source media="(min-width: 320px) and (max-width: 640px) and (orientation: portrait)" srcset="./img/lx2.png"> <!-- 橫屏 640px --> <source media="(min-width: 640px) and (orientation: landscape)" srcset="./img/lx.png"> <!-- 豎屏 640px--> <source media="(min-width: 640px) and (orientation: portrait)" srcset="./img/lx.png"> <!-- 默認 --> <img src="./img/lx.png" alt="this is a picture"> </picture> <script src="./polyfill.object-fit.min.js"></script> <script> document.addEventListener('DOMContentLoaded', function () { objectFit.polyfill({ selector: 'img', fittype: 'cover' }); }); </script> </body> </html> <!-- 解決圖片下的白邊 /* 第一種 display: block; */ /* 第二種 */ vertical-align:bottom; /* 第三種 img的父級容器,添加屬性overflow:hidden */ -->