简体   繁体   中英

How can I place an html element in some absolute coordinates regardless of the body style (position, margin) using JS?

I'm trying to place an element in a web site at a certain fixed amount of pixels from the viewport top border. The problem is that despite of using absolute positioning, the positioning still depends of the body style. For instance, if the body has relative positioning and a margin top value, then the position of my absolute-positioned element will be increased by the body margin top value. So, how can I make it independent of body style?

Note: I can't use any framework, just plain JS.

UPDATE: I want the position to be affected by the scroll, so "fixed" positioning is not an option. I also want it to be cross browser.

It's quite simple, however it won't work in IE7. You can use position:fixed to position an element in relation to the viewport(browser edges), regardless of what margins, padding or whatever else parent elements have.

To do this with javascript:

var container = document.getElementById('container');// This is your container. Replace accordingly.
var elementToInsert = document.createElement("div");// Create a new element.
elementToInsert.style.position ='fixed';// It will now position in relation to the viewport, regardless of where it is nested, etc.
elementToInsert.style.top = '100px';// Always add pixels, won't work otherwise.
elementToInsert.style.left = '300px';// Always add pixels, won't work otherwise.
elementToInsert.style.width = '500px';// Always add pixels, won't work otherwise.
elementToInsert.style.height = '500px';// Always add pixels, won't work otherwise.
container.appendChild(elementToInsert);// Append the new div to the container.

Also, you don't really need JS for this. Plain old HTML + CSS will do the trick just as well. Read more about CSS position:fixed; HERE

You just need to set position to fixed .

var div = document.createElement("div");
div.style.position = "fixed";
div.style.top = "0";
div.style.left = "0";
div.appendChild(document.createTextNode("Some Text"));
document.getElementsByTagName("body")[0].appendChild(div);

One trick that web developers use to iron out the differences between browsers is to use a css file to reset properties like body margins.

Example here: http://meyerweb.com/eric/tools/css/reset/

This assumes it isn't your css adding margins to the body.

Oops - I did this in jQuery anyway - I will leave it for future reference. Hope the downvoters can leave it too

This works in Chrome, Fx, IE8, IE9

DEMO

$(function() {
  $("img").on("click",function() { 
    $(this).offset({top:0,left:0}); 
  });
});    

​ which means you could do

$(function() {
  $("#myimg").offset({top:0,left:0}); 
});    

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