2016-11-21 68 views
1

我希望我的背景圖像能夠填充正在查看的窗口的高度。顯然我不知道這個值,因爲它是可變的。我知道使用jQuery做我想做的事情是可能的,但是在搜索到SO和Google大約一個小時之後,沒有找到我的問題的答案,我放棄了並決定詢問。如何使用jQuery設置背景圖像高度?

我有背景圖像設置爲覆蓋它包含<div>使用CSS。

我該如何達到預期的效果?

+0

它沒有用JS來完成。在這裏閱讀css'vh'屬性:[CSS Viewport Units](http://tutorialzine.com/2015/05/simplify-your-stylesheets-with-the-magical-css-viewport-units/) – winseybash

+0

你可以做這樣的事情:http://stackoverflow.com/questions/106828/javascript-get-image-height(不會有任何額外的開銷,如果你已經檢索圖像)儘管正如人們已經提到的,你可能根本不需要JS。 – DBS

+0

'background-size:auto 100%;' – Banzay

回答

4

根據窗口高度使用jquery背景圖片 查看片段


 

 
$(document).ready(function() { 
 
    var winHeight = $(window).height(); 
 
    $('.window-height-bg').css('height', winHeight + 'px'); 
 
});

 

 
body{ 
 
     margin:0px; 
 
    } 
 
    .window-height-bg { 
 
     width:100%; 
 
     background:red url(http://i67.tinypic.com/2mqj1iq.jpg) no-repeat; 
 
     background-size:100% 100%; 
 
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 

 
<div class="window-height-bg"> 
 
</div>

+0

我認爲這正是我需要的。我現在要測試它。 –

0

jQuery中試試這個:

$("#image_id").css({ 
    "background-image": "url(BG.jpg)", 
    "background-attachment": "fixed", 
    "background-size": "100%" // This size will be the 100% of the container 
}); 
1

嗨,你可以通過在圖像標記或DIV使用最大寬度屬性或者圖像設置爲身體標記

max-width: 100%; 

或實現它像這

<body background="http://ssmstorage.blob.core.windows.net/thumbnail/thumbnail_6e9579e9-ec17-4fce-a8cb-6421322b5460.jpg"> 
0

這是一個腳本,採用div的背景,並將其設置爲身體的BG和設置圖像高度t爲100vh。您可以替換"body"通過下面的代碼procecced全屏包含分區"div"

$("div").on("click", function() { 
    var bg = $(this).css("background-image"); 
    $("body").css("background-image", bg); 
    $("body").css("background-size", "auto 100vh"); 
}); 
0

我覺得這下面的代碼將幫助您

請檢查鏈接瞭解更多詳細Link

<body background="w3s.png"> 
<img style=" display: inline-block; 
    max-width: 100%; 
    vertical-align: middle;" src="http://ssmstorage.blob.core.windows.net/thumbnail/thumbnail_6e9579e9-ec17-4fce-a8cb-6421322b5460.jpg" alt="Smiley face" width="50%" height="50%"> 
<h1>dfksdhfsdfklsdfhsdklfhlskfsdlfjklsf</h1> 
<img style=" display: inline-block; 
    max-width: 100%; 
    vertical-align: middle;" src="http://ssmstorage.blob.core.windows.net/thumbnail/thumbnail_6e9579e9-ec17-4fce-a8cb-6421322b5460.jpg" alt="Smiley face" width="50%" height="50%"> 
<h1>dfksdhfsdfklsdfhsdklfhlskfsdlfjklsf</h1> 
<img style=" display: inline-block; 
    max-width: 100%; 
    vertical-align: middle;" src="http://ssmstorage.blob.core.windows.net/thumbnail/thumbnail_6e9579e9-ec17-4fce-a8cb-6421322b5460.jpg" alt="Smiley face" width="50%" height="50%"> 
</body>