使用css将JS变量移动到图像中心

时间:2014-11-25 10:07:19

标签: javascript html css variables

我使用Javascript解决了一个基本问题。我现在希望我的结果看起来不仅仅是将数字打印到屏幕上。当显示某些结果时,我会显示各种图像。对于一个特定的结果虽然' x'我希望数字显示在图像的中心。我尝试将结果插入带有背景图像的div中,但无法将结果置于中心位置x'到图像的中心。有没有办法做到这一点?我感谢任何帮助,或者至少指出了正确的方向。

还创建了一个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;
}

1 个答案:

答案 0 :(得分: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;
}