2016-11-21 47 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>