2015-09-08 35 views
1

嗨,並希望你能幫助。我的JavaScript不是那麼熱門,我嘗試過搜索,但沒有找到正確的方法。jquery添加動態url的背景圖片

我想添加CSS背景圖像到div(.jumbotron),但動態更改url取決於屏幕大小。圖像將來自https://unsplash.it其中URL可以被編碼到尺寸有所回升需要即 https://unsplash.it/200/300

<script type="text/javascript"> 
function setBackground() { 
    $('jumbotron').css('background-image', 'url(https://unsplash.it/' + $(window).height(); + '/' + $(window).width();')'); 
} 
</script> 

我希望這是有意義的,並在此先感謝

+3

什麼是jumbotron?它是一個id /類嗎?它可能需要一個選擇器標籤(例如'.jumbotron'或'#jumbotron')。此外,您在關閉腳本標記上還有一個額外的'>'。 –

回答

2

假設jumbotron是一個ID或類,使確定你給它一個選擇器標籤。

你可以做這樣的事情來實現你想要什麼:JS Fiddle

function setBackground() { 
    var height = $(window).height(); 
    var width = $(window).width(); 
    $('.jumbotron').css('background-image', 'url(https://unsplash.it/' + width + '/' + height + ')'); 
} 

說明你原來的:
jumbotron需要選擇標籤(類別/ ID)
$(window).width();缺少一個它後面有+
對於Upslash鏈接,寬度需要在高度之前正常工作。

一注:
你想讓這個函數在加載時運行嗎?如果是這樣,一定要調用該函數,因爲它沒有設置爲立即運行。

+0

你是一個絕對的明星。非常感謝。 –

0

嘗試刪除字符串中的分號。

function setBackground() { 
    $('jumbotron').css('background-image', 'url(https://unsplash.it/' + $(window).height() + '/' + $(window).width()')'); 
} 

在字符串中間有一個分號會強制它在字符串完成之前停止。

0

試試這個: -

<script type="text/javascript"> 
function setBackground() { 
$('jumbotron').css('background-image', 'url(https://unsplash.it/' + $(window).height(); + '/' + $(window).width(); + ')'); 
} 
</script>> 

你已經錯過寬度後的 '+' 號。

+0

嘗試上面的代碼。 –