繁体   English   中英

如何使用JS将html元素放在一些绝对坐标中,而不管体型(位置,边距)如何?

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

我正在尝试在视口顶部边框的某个固定数量的像素的网站中放置一个元素。 问题是尽管使用绝对定位,定位仍然取决于身体风格。 例如,如果主体具有相对定位和边缘顶部值,那么我的绝对定位元素的位置将增加主体边缘顶部值。 那么,我怎样才能让它独立于身体风格呢?

注意:我不能使用任何框架,只需简单的JS。

更新:我希望位置受滚动影响,因此“固定”定位不是一个选项。 我也希望它是跨浏览器。

这很简单,但在IE7中不起作用。 您可以使用position:fixed来相对于视口(浏览器边缘)定位元素,无论边距,填充或其他任何父元素都有。

要使用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.

此外,你真的不需要JS。 简单的旧HTML + CSS也可以做到这一点。 阅读更多关于CSS position:fixed; 这里

你只需要将position设置为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);

Web开发人员用来消除浏览器之间差异的一个技巧是使用css文件来重置身体边距等属性。

示例: http//meyerweb.com/eric/tools/css/reset/

这假设它不是你的css向身体添加边距。

哎呀 - 无论如何我在jQuery中这样做了 - 我将把它留待将来参考。 希望downvoters也可以离开它

这适用于Chrome,Fx,IE8,IE9

DEMO

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

这意味着你可以做到

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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