使用媒体查询Angular.js数据绑定背景图片 [英] Angular.js data-bind background images using media queries
问题描述
我有一个动态的背景图像的应用Angular.js(应该有自己的URL数据绑定)。我也想为了使用CSS媒体查询来检测方向/像素密度等。
I have an Angular.js application with dynamically background images (should have data-binding for their URL). I also want to use css media queries in order to detect orientation/pixel density etc.
我发现的唯一的解决方法是使用javascript URL添加到背景图像,像这样:
The only solution I found is using javascript to add URL to the background image, something like this:
myDiv.css({'background' : 'url('+ scope.objectData.poster +') no-repeat', 'background-size':'auto 100%'});
这样,我必须通过所有媒体查询逻辑的JavaScript,像这。 (我的目的是能够提供不同的背景图像的每个屏幕分辨率/像素密度/方位)
This way I have to pass all media queries logic to javascript, something like this. (My intention is to be able to serve different background image for each screen resolution / pixel density / orientation)
我要寻找一个更清洁的解决方案中使用CSS媒体查询,仍然能够数据绑定我的形象的来源。
I am looking for a cleaner solution to use css media queries and still be able to data-bind my image sources.
TNX!
亚尼夫
推荐答案
这只是一个起点,解决您的问题。
This is just a starting point solving your problem.
您可以使用matchMedia:的https://developer.mozilla .ORG / EN-US /文档/网络/ API / Window.matchMedia
You may use matchMedia: https://developer.mozilla.org/en-US/docs/Web/API/Window.matchMedia
if (window.matchMedia("(min-width: 400px)").matches) {
$scope.poster = 'small.png';
} else {
$scope.poster = 'big.png';
}
现在你可以在HTML文件中使用它:
now you can use it in the html file:
<div class="moments-preview-image"
ng-style="{'background-image': 'url('+poster+ ')'}"> ... </div>
如果你的浏览器不支持此新的API,你可以有一些有趣的解决方法请看:
If your browser doesn't support this new API you may have a look on some interesting workarounds:
http://wicky.nillia.ms/enquire.js/
http://davidwalsh.name/device-state-detection- CSS媒体查询JavaScript的
这篇关于使用媒体查询Angular.js数据绑定背景图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!