Mixing handlebars.js and CSS - Random background image?

纵然是瞬间 提交于 2019-12-06 16:05:38

This approach ended up working for me:

I'm using an internal stylesheet that I define as a template. The url is updated to match the randomly generated url:

<template name="backgroundImage">
  <style>
  body {
  background-image:url({{background}});
  background-repeat: no-repeat;
  background-position: right top;
  }
  </style>

Meteor has a package built for meteor called random you can add with

meteor add random

If it is not included in your project already.

The Random.choice() method could help you e.g if you have an array of URLs

var myurls = ["http://www.url.com/1","http://www.url.com/2","http://www.url.com/3"];
var the_random_url = Random.choice(myurls);

Then as you mentioned alter the 'body' with css & a handlebars helper for {{background}}

<style>
    body {
        background-image:url({{background}});
        background-repeat: no-repeat;
        background-position: right top;
    }
</style>

Or edit it with jquery:

$('body').css({
    background-image:"url("+the_random_url+")",
    background-repeat: "no-repeat"
    background-position: "right top"
});

sugarjs provides a sample() method

http://sugarjs.com/api/Array/sample

or you can check source to write your own.

https://github.com/andrewplummer/Sugar/blob/master/lib/array.js#L906

Returns a random element from the array. If num is passed, will return num samples from the array.

i use this on my meteor.js project. use that api i get random elements after template rendered.

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