2014-11-25 33 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