2014-11-25 41 views
0

我使用Javascript解決了一個基本問題。我現在希望我的結果看起來比只是將數字打印到屏幕上更好。當顯示特定結果時,我會顯示各種圖像。對於一個特定的結果,雖然'x'我希望數字顯示在圖像的中心。我嘗試將結果插入帶有背景圖像的div,但無法將'x'居中放置到圖像的中心。有沒有辦法做到這一點?我感謝任何幫助或至少指出了正確的方向。使用css將JS變量移動到圖像中心

而且(用這個點擊取消就彈出一個對話框,它會爲你帶來直接的代碼。很抱歉,如果我做錯了什麼,還是第一次。)創建的jsfiddle

http://jsfiddle.net/codemesoftly/yo5Lt92t/

var userChoice = prompt("Pick a number between 50 and 100"); 

for (x=1; x <= userChoice; x++){ 
    if(x % 3 == 0){ 
     document.write("<ul><img src='http://dtc-wsuv.org/rgrover14/pingpong/left.png'></ul>") 
    } 
    if(x % 5 == 0){ 
     document.write("<ul><img src='http://dtc-wsuv.org/rgrover14/pingpong/right.png'></ul>") 
    } 
    if((x % 3 != 0) && (x % 5 != 0)){ 
     document.write("<div id='ball'><ul>" + x + "</ul></div>") 
    } 
} 

#ball { 
    background-image: url('http://dtc-wsuv.org/rgrover14/pingpong/ball.png'); 
    background-repeat: none; 
    height: 96px; 
    width:96px; 
} 

ul { 
    margin-top: 5px; 
} 

回答

0

你可以嘗試這樣的事情:

var userChoice = 4; //prompt("Pick a number between 50 and 100"); 

for (x=1; x <= userChoice; x++){ 
    if(x % 3 == 0){ 
     var div = document.createElement('div'); 
     div.className = 'ball'; 
     div.textContent = x; 
     div.style.textAlign="center"; 
     div.style.verticalAlign='middle'; 
     div.style.display='table-cell'; 
     document.body.appendChild(div); 
    } 
} 


.ball { 
    background-image: url("http://dtc-wsuv.org/rgrover14/pingpong/ball.png"); 
    background-repeat: none; 
    height: 96px; 
    width:96px; 
} 
+0

其他方式垂直居中的文本,也與這裏舊的瀏覽器的兼容性評論:http://stackoverflow.com/questions/88654 58/how-to-align-text-vertical-center-in-div-with-css – Butterfly 2014-11-25 11:08:11

+0

謝謝!這就是茉莉花必須在魔毯上感受到阿拉丁的感覺。一個全新的世界!它對我正在嘗試做的事情非常有幫助。還有很多東西需要學習,這對我們有很大的幫助。 – Ryan113 2014-11-26 00:06:37