简体   繁体   中英

How do I position a character at a specific coordinate in a page with JavaScript

I tried this code:

var span = document.createElement('span')
span.style.position = 'absolute'
span.style.color = 'red'
span.style.left = 100
span.style.top = 100
span.innerHTML = '*'
document.body.insertBefore(span, document.body.firstChild)

But this code still positions the asterisk at coordinate (0, 0) instead of (100, 100). Here is a jsfiddle URL: http://jsfiddle.net/E5NDV/

Could you please help me in getting this right?

var span = document.createElement('span')
span.style.position = 'absolute'
span.style.color = 'red'
span.style.left = "100px"
span.style.top = "100px"
span.innerHTML = '*'
document.body.insertBefore(span, document.body.firstChild)

http://jsfiddle.net/E5NDV/1/

The values for left and top should be a String giving a number and a unit, eg px for pixels , ie '100px' . Which child the node is appended as does not matter so much for absolute positioning as this information is not used to decide where to position it, using appendChild would work just as well as insertBefore .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM