2014-02-19 31 views
1

我想創建一個簡單的幻燈片放映設置和背景div的圖像。我沒有創建幻燈片代碼的問題,但我有定位應該根據其他顯示器分辨率的寬度而改變的圖像的問題。JavaScript和CSS定位圖像的任何分辨率

在我描述的圖像波紋管是我想放置圖像。圖像應該放在紅色的div中。

enter image description here

這裏是我想要把紅色div來像一個背景圖像。分辨率爲(1900px X 500像素)

enter image description here

這裏是一個模型是我能夠做到。我試圖在java腳本代碼中聲明一個全局變量sw,我分配了window.innerWidthsw=window.innerWidth),之後在CSS中使用jquery選擇了紅色的格子$('#rotator')並指定了sw$('#rotator').css('width', sw)),但結果並非我所需要的。根據屏幕分辨率,我獲得了從右側裁剪的圖像。 enter image description here

如果有人知道如何解決這個問題,我將是偉大的!

這是我碼:

HTML

<!DOCTYPE html> 
<html> 
<head> 
    <link rel="stylesheet" type="text/css" href="style.css"> 
    <script type="text/javascript" src="jquery-2.1.0.js"></script> 
    <script type="text/javascript" src="function.js"></script> 
    <script src="jquery.easing.1.3.js"></script> 
    </head> 
<body > 
    <div id="rotator"></div> 
    <div class='slider'></div> 
</body> 
</html> 

CSS

body{ 
    margin: 0px; 
    margin-left: 0px; 
} 

.slider{ 
    width: 940px; 
    height: 360px; 
    background-color: #FFDF00; 
    margin: 0 auto; 
    position: absolute; 
    left: 15%; 
    top: 20px; 
    } 

#rotator { 
    position: relative; 
    height: 500px; 
} 

.puzzle { 
    width: 100px; 
    height: 100px; 
    background-position: -100px 0px; 
    float: left; 
} 

和JavaScript也包含幻燈片效果的功能(即工作)。

$(document).ready(init) 

sw=window.innerWidth; 

if (sw % 100 == 0) { 
    sw=window.innerWidth 
} 
else{ 
    sw=Math.floor(sw/100)*100 
} 


//counter of slider 
current_slide=0; 
image_list=new Array 
(
"img/1.jpg", 
"img/2.jpg",  
"img/3.jpg", 
"img/4.jpg", 
"img/5.jpg" 
); 

function init() 
{ 
    $('#rotator').css('width', sw) 
    change(image_list[current_slide]); 
    //start timer 
    setInterval( "change(image_list[current_slide])" ,2500); 
} 

function change(bg_image){ 
    // this function creats cells inside <div id = 'rotator'> 
    rot = $('#rotator'); //constructor 
    rot.empty(); 
    for(y = 1; y<=5; y++) 
    { 
     for(x = 1; x<=sw/100; x++) 
      { 
      rot.append('<div class = "puzzle p-' + x + '-' + y + ' "></div>'); 
      //select the <div> using his class and setting up the cells coordinates 
      $('.p-' + x + '-' + y).css('background-position', (-(x-1)*100) + 'px ' + (- (y-1)*100) + 'px').css('background-image','url('+bg_image+')'); 
      $('.p-' + x + '-' + y).css('opacity', 0).delay(parseInt(Math.random()*1000)).animate({opacity: 1}, {duration: 1000}) 
      } 
    } 
    current_slide++; 
    if(current_slide >= image_list.length)current_slide=0 
} 

謝謝你的時間和考慮!

+0

究竟什麼是您的問題?很難分辨這麼多的信息。 – Jasper

+0

你喜歡做什麼?你想把你的形象放在所有其他元素的頂部嗎? –

+0

問題是,背景圖像,那個與槍,沒有調整大小,它只是根據屏幕的寬度從右側裁剪。 – Chris

回答

4

您必須將圖像放入容器div,其寬度對頁面大小是動態的,並將其中的圖像寬度設置爲100%,或使用CSS屬性background-size: cover;(它僅與較新的瀏覽器)。

設置爲div的背景圖像的圖像將簡單地填充其容器,並在容器縮小超過背景圖像的尺寸時被該容器剪切,除非使用background-size: cover;。爲了在舊版瀏覽器中獲得相同的效果,使用前面提到的100%技巧。

跨瀏覽器的風格: http://jsfiddle.net/2D5Vw/

新(ISH)-School: http://jsfiddle.net/HLf2Q/

+0

在JS小提琴中加入工作示例來回答。 – StephenRios