最簡單的方法是創建一個重定向到隨機圖像的操作,瀏覽器將遵循重定向。
應用程序/控制器/ background_controller.rb
class BackgroundController < ApplicationController
def image
redirect_to "/assets/images/background_#{rand(10)}.jpg"
end
end
這將隨機重定向到background_0.jpg
和background_9.jpg
配置/ routes.rb中
Something::Application.routes.draw do
…
get '/random_background.jpg', to: 'background#image'
…
end
CSS
之間的背景圖像
html{
background: url(/random_background.jpg) no-repeat center center fixed;
}
一些更高級的做法是在中間件中這樣做,所以這樣的請求不需要整個軌道堆棧。
應用/中間件/ random_background_middleware.rb
class RandomBackgroundMiddleware
def initialize(app, count = 10)
@app = app
@count = count
end
def call(env)
if env["PATH_INFO"] == "/random_background.jpg"
[302, {"Location" => "/assets/images/background_#{rand(@count)}.jpg")}, '']
else
@app.call(env)
end
end
end
config/application.rb
config.middleware.insert_before 0, "RandomBackgroundMiddlware"
insert_before 0
用於將其放置在中間件鏈的頂部
甚至更好在你的web服務器配置中會是這樣的。但我不知道如何或如果這可以做到。
[你有什麼試過](http://whathaveyoutried.com/)? –
我到目前爲止嘗試過:random_bg = ['bg1.png','bg2.png','bg3.png']。sample。不幸的是,這些圖片並沒有顯示出來:( – MFCS