【问题标题】:Show a box on top of an image in an HTML page在 HTML 页面中的图像顶部显示一个框
【发布时间】:2014-07-09 02:43:43
【问题描述】:

我有一个简单的 HTML5 页面,显示一个(相当大的)布局图像,其中包含一堆编号的框。基于一个选择元素,我想在图像上的特定编号框上显示一个红色的空心框。

这是我目前所拥有的:

    <div data-role="content" style="scrolling: scroll; position: relative;">
         <div style="float:left; position: absolute; border: 2px solid red; left: 154px; top: 52px; width: 20px; height: 20px;"></div>
         <img alt="Floor Plan" src="../common/images/floorplan.jpg" width="100%" />
    </div>

结果如下图:

我想我可以在一个javascript数组中预先填充每个编号框的坐标和每个框的宽度和高度,然后根据选择列表,我可以动态更改框div对应的CSS元素。然而让我感到困惑的是,当浏览器调整大小时,图像会自动缩小(我使用的是 Firefox,但我想这在大多数浏览器中很常见),但框不会随之缩放。

如何解决这个问题,最好使用 CSS?也欢迎任何其他解决方案。提前致谢。

【问题讨论】:

  • 您可以按百分比计算坐标。
  • @WesleyMurch 感谢您的建议 - 这很有帮助。
  • 做得很好。我以前必须用一个复杂的锦标赛支架来做到这一点。回想起来我会做不同的事情,但当时似乎更容易将结果叠加在图像背景上。

标签: css html


【解决方案1】:

我能够根据本网站上的一些答案和@WesleyMurch 提供的提示推出解决方案。本质上,我必须分别计算高度和宽度比例(我原以为它们会相同,但事实并非如此!),然后将比例因子应用于原始左侧和顶部坐标以获得缩放的左侧和顶部坐标.最后,必须使用离线计算以百分比形式指定高度和宽度。

解决方案如下所示:

<html>
<head>
<title>Test</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript" charset="utf-8">
    function positionBox(event, x, y)
    {
        // Get the dimensions of the rendered image
        var renderedImg = event.currentTarget;
        var cw = $(renderedImg).width();
        var ch = $(renderedImg).height();

        // Get the dimensions of the original image
        var originalImage = document.getElementById("testImg");
        var nw = originalImage.naturalWidth;
        var nh = originalImage.naturalHeight;

        var newx = Math.floor((x * cw)/nw);
        var newy = Math.floor((y * ch)/nh);

        $("#redBox").css("left", newx + "px");
        $("#redBox").css("top", newy + "px");
        $("#redBox").css("visibility", "visible");

        alert("Current image dim = (" + cw + "," + ch + "), natural dim = (" + nw + ", " + nh + "), new top-left = (" + newx + ", " + newy + ")");
    }
</script>  
</head>
<body>
<div style="scrolling: scroll; position: relative;">
    <div id="redBox" style="float:left; position: absolute; border: 2px solid red; left: 0; top: 0; width: 6.3%; height: 4.6%; visibility: hidden;"></div>
    <img id="testImg" alt="Floor Plan" src="floorplan.jpg" width="100%" onload="positionBox(event, 918, 626);" />
</div>
</body>
</html>

希望这对某人有所帮助。一些支持线程是hereherehere

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-14
    • 1970-01-01
    • 2020-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-12
    相关资源
    最近更新 更多