javascript - 使用CSS将JS变量移动到图像内部居中

标签 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;
}

最佳答案

你可以尝试这样的事情:

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;
}

关于javascript - 使用CSS将JS变量移动到图像内部居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27123776/

相关文章:

由于...CSS,PHP 邮件表单文本框无法编辑?

java - 如何操作java中的类

javascript - 为什么atob和btoa在使用上没有区别?

html - 多列列表可以有单独的 flex 列吗?

javascript - 输入类型文件,如何在屏幕上显示图像?

javascript - 在不重新加载的情况下更改 HTML 页面上的特定元素

javascript - 单击表格行时显示额外数据

javascript - 替代 OR 语句

css - 按类别选择除最后一个以外的所有类别

javascript - 如何用文本创建 td 边框