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

例如:

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

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


当前回答

如果你将规则添加到print.css文件中,你不必使用@media。

我在我用来给一些元素一个背景色的smarty foreach中去掉了它。

< script type = ' text / javascript ' > document.styleSheets[3]。insertRule(“# caldiv_ < ?smarty美元项目。Calendar_id ?> {border-color:<?smarty美元项目。Color ?>}", 1); > < /脚本

其他回答

如果您正在使用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>

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

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

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

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

您可以使用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);">

样式-属性的媒体查询现在不可能。 但如果你必须通过Javascript动态设置。 你也可以通过JS插入该规则。

document.styleSheets[0].insertRule("@media only screen and (max-width : 300px) { span { background-image:particular_ad_small.png; } }","");

这就好像样式就在样式表中一样。所以要注意特殊性。

如果你将规则添加到print.css文件中,你不必使用@media。

我在我用来给一些元素一个背景色的smarty foreach中去掉了它。

< script type = ' text / javascript ' > document.styleSheets[3]。insertRule(“# caldiv_ < ?smarty美元项目。Calendar_id ?> {border-color:<?smarty美元项目。Color ?>}", 1); > < /脚本