Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
461 views
in Technique[技术] by (71.8m points)

javascript - Angular.js data-bind background images using media queries

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...