我需要动态加载横幅图像到HTML5应用程序,并希望几个不同的版本,以适应屏幕宽度。我不能正确地确定手机的屏幕宽度,所以我能想到的唯一方法是添加div的背景图像,并使用@media来确定屏幕宽度并显示正确的图像。

例如:

 <span style="background-image:particular_ad.png; @media (max-width:300px){background-image:particular_ad_small.png;}"></span>

这可能吗,或者有人有其他建议吗?


当前回答

是的,如果你正在使用图片标签,你可以在inline-css中编写媒体查询。对于不同的设备大小,您可以得到不同的图像。

<picture>
    <source media="(min-width: 650px)" srcset="img_pink_flowers.jpg">
    <source media="(min-width: 465px)" srcset="img_white_flower.jpg">
    <img src="img_orange_flowers.jpg" alt="Flowers" style="width:auto;">
</picture>

其他回答

您可以使用image-set()

<div style="
  background-image: url(icon1x.png);
  background-image: -webkit-image-set(  
    url(icon1x.png) 1x,  
    url(icon2x.png) 2x);  
  background-image: image-set(  
    url(icon1x.png) 1x,  
    url(icon2x.png) 2x);">

如果您正在使用Bootstrap Responsive Utilities或类似的替代方法,允许根据断点隐藏/显示div,则可能使用几个元素并显示最合适的元素。即。

 <span class="hidden-xs" style="background: url(particular_ad.png)"></span>
 <span class="visible-xs" style="background: url(particular_ad_small.png)"></span>

是的,你可以通过window.matchMedia使用javascript

桌面为红色文本 绿色文字的平板电脑 移动为蓝色文本

//isat_style_media_query_for_desktop_mobile_tablets var tablets = window.matchMedia("(max-width: 768px)");//for tablet devices var mobiles = window.matchMedia("(max-width: 480px)");//for mobile devices var desktops = window.matchMedia("(min-width: 992px)");//for desktop devices isat_find_device_tablets(tablets);//apply style for tablets isat_find_device_mobile(mobiles);//apply style for mobiles isat_find_device_desktops(desktops);//apply style for desktops // isat_find_device_desktops(desktops,tablets,mobiles);// Call listener function at run time tablets.addListener(isat_find_device_tablets);//listen untill detect tablet screen size desktops.addListener(isat_find_device_desktops);//listen untill detect desktop screen size mobiles.addListener(isat_find_device_mobile);//listen untill detect mobile devices // desktops.addListener(isat_find_device_desktops); // Attach listener function on state changes function isat_find_device_mobile(mob) { // isat mobile style here var daynight=document.getElementById("daynight"); daynight.style.color="blue"; // isat mobile style here } function isat_find_device_desktops(des) { // isat mobile style here var daynight=document.getElementById("daynight"); daynight.style.color="red"; // isat mobile style here } function isat_find_device_tablets(tab) { // isat mobile style here var daynight=document.getElementById("daynight"); daynight.style.color="green"; // isat mobile style here } //isat_style_media_query_for_desktop_mobile_tablets <div id="daynight">tricky style for mobile,desktop and tablet</div>

他们没有在HTML级别上考虑媒体查询,这是疯狂的,因为很明显样式css是在HTML之后加载的,在HTML内部内联样式是一个巨大的缺点。

通过使用像Breakpoint for Sass这样的东西,可以实现内联媒体查询

这篇博客文章很好地解释了内联媒体查询如何比单独的块更易于管理:There Is No Breakpoint

与内联媒体查询相关的是“元素查询”的思想,一些有趣的阅读是:

关于元素媒体查询的思考 媒体查询是一种Hack 媒体查询不是答案:元素查询填充 If else块