Angular.js data-bind background images using media queries

爷,独闯天下 提交于 2019-12-18 08:50:15

问题


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.

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%'});

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)

I am looking for a cleaner solution to use css media queries and still be able to data-bind my image sources.

tnx!

Yaniv


回答1:


This is just a starting point solving your problem.

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';
}

now you can use it in the html file:

<div class="moments-preview-image" 
    ng-style="{'background-image': 'url('+poster+ ')'}"> ... </div>

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



来源:https://stackoverflow.com/questions/21000338/angular-js-data-bind-background-images-using-media-queries

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!