使用媒体查询的 Angular.js 数据绑定背景图像 [英] Angular.js data-bind background images using media queries

查看:30
本文介绍了使用媒体查询的 Angular.js 数据绑定背景图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有动态背景图像的 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.(我的目的是能够为每个屏幕分辨率/像素密度/方向提供不同的背景图像)

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/docs/Web/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-media-queries-javascript

这篇关于使用媒体查询的 Angular.js 数据绑定背景图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆