如何缩放背景图像并使其适用于浏览器大小

时间:2013-03-17 21:06:51

标签: javascript jquery html css html5

我想要的是我的div中的背景图像会缩放,以便覆盖整个浏览器。如果图像太小,它会增加,如果它变大,它会变小。我不希望图像重复。

See live demo of my whole web design by clicking here.

我的parallex设计中的每个部分都是。它们看起来像这样:

<section id="start" data-type="background" data-speed="10" style="background: url('http://media.vogue.com/files/2013/01/15/storm-troupers-02_191346273703.jpg') 50% 0 repeat fixed; min-h-margin: 0 auto; height: 1080px;">
    bla bla bla     
</section>

样式表

section {
    width: 100%; 
    max-width: 1920px; 
    height: 1080px;
    position: relative; 
    padding-bottom: 40px;
}

还有一个用于parallex滚动的jquery脚本。在这里有一个背景位置的脚本。这可能会影响某些事情

/**
 * Parallax Scrolling Tutorial
 * For NetTuts+
 *  
 * Author: Mohiuddin Parekh
 *  http://www.mohi.me
 *  @mohiuddinparekh   
 */


$(document).ready(function(){
    // Cache the Window object
    $window = $(window);

   $('section[data-type="background"]').each(function(){
     var $bgobj = $(this); // assigning the object

      $(window).scroll(function() {

        // Scroll the background at var speed
        // the yPos is a negative value because we're scrolling it UP!                              
        var yPos = -($window.scrollTop() / $bgobj.data('speed')); 

        // Put together our final background position
        var coords = '50% '+ yPos + 'px';

        // Move the background
        $bgobj.css({ backgroundPosition: coords });

}); // window scroll Ends

 });    

}); 
/* 
 * Create HTML5 elements for IE's sake
 */

document.createElement("content");
document.createElement("section");

1 个答案:

答案 0 :(得分:2)

您可以使用CSS background-size属性。

section {
    background-size: 100%;
}

min-h-margin不是有效的CSS属性。我不确定你用的是什么,或者如果这是一个错字,但我认为值得指出。

您还应注意section可能未在此处正确使用。来自HTML5 specification

  

section元素不是通用容器元素。当一个元素仅用于样式目的或作为脚本编写的便利时,鼓励作者使用div元素。

来自以下评论的

修改

  

...但是当浏览器未全屏显示时,您可以看到背景重复。

background-repeat: repeat repeat;上的sections替换为:

background-repeat: no-repeat;