首页 > 解决方案 > object-fit: cover; stops working on dynamically added (Safari bug?)

问题描述

I have a weird one... Just spent hours trying to tackle a Safari bug where object-fit: cover; stops working on a dynamically added img elements.

Maybe there is a workaround? Or maybe someone has any idea what is going on? I am unable to wrap my head around this one.

I have isolated the bug in this small test site: https://safaribug.000webhostapp.com/

Just press Next page on Safari (it loads the same page just with a new next page URL).

How if should look like

How it looks after page navigation

标签: javascripthtmlcsssafari

解决方案


If anyone else stumbles open this bug, the solution that worked for me was to:

  • Detect if the browser is Safari
  • If it is, then once the HTML was put to the dom, loop through each image and force it to re-render. In my case I just removed srcset attribute and put it back again like so:
    document.querySelectorAll('picture.image > img')
            .forEach($img => {
              const srcset = $img.getAttribute('srcset');
              $img.setAttribute('srcset', '');
              $img.setAttribute('srcset', srcset);
            });

Not a solution I was looking for, but it works.


推荐阅读