javascript - 在 HTML + CSS 中将对象定位在图像上

标签 javascript html css image css-position

我正在用 HTML、CSS + Javascript 制作一个找不同的游戏,但我面临的一个问题是在不同的分辨率下,标记圆圈和点击框(基本上只是一个链接到的图像一个在标记圈中淡出的 javascript 函数)都在错误的地方。

我在 CSS 中使用百分比值的绝对定位。标记和点击框覆盖的主图像占页面宽度和高度的 50%。

谢谢,

尼尔。

编辑:添加了关于主图像的信息

最佳答案

更新:您的编辑:

The main image that the markers and hitboxes get overlaid on is 50% width and height of the page.

...大大改变了问题。 :-) 我在下面关于使用像素值覆盖的回答仍然有效;但是计算它们的位置变成了一场噩梦,因为您无法在设计时知道图像的实际宽度。这意味着您必须在运行时找出图像的实际宽度/高度(例如,通过 JavaScript),然后调整您用于绝对定位其他所有内容的像素值以解决这个问题。

如果您可以避免它(例如,只提供一些标准尺寸),我建议您避免使用它。如果你不能,我建议使用库(如 jQueryPrototypeYUIClosureany of several others)来发现图像的实际计算宽度和高度。


原始答案:

I'm using absolute positioning in CSS with percentage values.

那就是问题所在。如果您想准确地将某些东西放在图像的顶部,因为图像中的像素是固定的,您需要使用像素值而不是百分比,例如 ( live example ):

CSS:

#main {
  /* Ensure that #main is an offset container */
  position: relative;
}
#main img {
  /* Position the image at 0,0 */
  position: absolute;
  left: 0px;
  top: 0px;
}
#main div {
  /* Position the div at 16,16 (middle of the 32x32 image */
  position: absolute;
  left: 16px;
  top: 16px;
  background-color: white;
  border: 1px solid black;
  padding: 1px;
}

HTML:

<body>
  <p>Positioning example:</p>
  <div id='main'>
    <img src='http://www.gravatar.com/avatar/2f37f49d08a02f40fe0c86529969c47a?s=32&d=identicon&r=PG'>
    <div>This starts half-way into and half-way down your gravatar</div>
</body>

关于javascript - 在 HTML + CSS 中将对象定位在图像上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4297666/

相关文章:

html - 如何让背景拉伸(stretch)到全宽?

css - 为 Wordpress 的按钮菜单 CSS 加下划线

javascript - jQuery — 如何使用高度 :auto 为 div 设置动画

javascript - 为什么 `isArray()` 写在 `Array` 而不是 `Array prototype` 上?

javascript - 在 React 中更改 mousedown 和 mousemove 的宽度

javascript - 使用 angularjs 创建水平单选按钮

javascript - 无论对象数组中的深度如何,获取键值

javascript - 模态中出现奇怪的符号而不是内容

CSS 功能区菜单导致内容和标题之间出现间隙

css - 使用 Bootstrap 的移动设备上 <body> 的空白左边距