js调整图像大小

时间:2011-08-19 02:10:16

标签: javascript jquery css3

<script type="text/javascript">
function carousel_bg(id) {
    var bgimgs = ['1920x625_Sonata_homepage_image.jpg', '1920x625_Equus_homepage_image.jpg', '5_home_hero_1920x625_CF_background.jpg']; // add images here..               
    var img = bgimgs[id];
    var cnt = 3; // change this number when adding images..                
    $('#body').css("background-image", "url(http://www.pitstopmotors.com.ph/images/" + img + ")");
    id = id + 1;
    if (id == cnt) id = 0;
    setTimeout("carousel_bg(" + id + ")", 10000);
}
$(document).ready(function() {
    carousel_bg(0);
});
</script>
</head>
  <body id="body">

我正在使用上面的代码将我的背景作为旋转木马,但图像并不完美。任何人都可以帮我添加一个函数到脚本,这将允许我添加这些样式宽度:100%;         位置:绝对;         顶部:0;         左:0;感谢

2 个答案:

答案 0 :(得分:0)

试试这个。而不是硬编码cnt=3,您可以获得数组长度。您无法将背景图像的位置设置为绝对值。

 function carousel_bg(id) {
    var bgimgs = ['bg_img1.jpg']; // add images here.. 
    var img = bgimgs[id]; 
    var cnt =        bgimgs.length; // made it dynamic 
    $('#main').css({
        "background-image": "url(http://www.pitstopmotors.com.ph/images/" + img + ")",
        "position": "absolute",
        "top": "0px",
        "left": "0px"}); 

    id = id + 1; 
    if (id==cnt) 
      id = 0;

    setTimeout("carousel_bg("+id+")", 10000); 
} 

$(document).ready(function() { carousel_bg(0); });

答案 1 :(得分:0)

只需将此行添加到#body元素:

的css处
$('#body').css({
"background-image": "url(http://www.pitstopmotors.com.ph/images/" + img + ")",
"position": "absolute",
"top": 0,
"left": 0});