【发布时间】:2014-10-29 09:39:17
【问题描述】:
我有一个响应式图像,其位置在父容器中是相对的。在同一个父容器中,我有一个位置:绝对固定在具有更高 z-index 值的图像上。
图钉显示在静态设计的正确位置,但如果我想让它用于响应式设计,看起来浏览器无法正确计算百分比并且图钉未显示在正确位置。
为了解决这个问题,我使用了 jquery,它以像素为单位计算响应式 img 大小,并以像素为单位计算 pin 的 css 左侧和顶部位置。但这仍然行不通。
HTML
<div class="col-xs-12" id="map">
<img src="../img/world-map.jpg" alt="world-map" id="world-map">
<a href="#" class="sydney" data-toggle="modal" data-target="#sydney-modal"></a>
<a href="#" class="melbourne" data-toggle="modal" data-target="#sydney-modal"></a>
<a href="#" class="perth" data-toggle="modal" data-target="#sydney-modal"></a>
<a href="#" class="singapore" data-toggle="modal" data-target="#sydney-modal"></a>
<a href="#" class="hongkong" data-toggle="modal" data-target="#sydney-modal"></a>
<a href="#" class="india" data-toggle="modal" data-target="#sydney-modal"></a>
<a href="#" class="china" data-toggle="modal" data-target="#sydney-modal"></a>
</div> <!-- end col map-->
测试页面链接:http://test.nsg.unsw.edu.au/contact/
少
#map
{
position:relative;
#world-map
{
width:100%;
z-index:-100;
} //end word-map
.sydney{
position:absolute;
width:12px;
height:12px;
background-color:red;
/*left: 81.5%;
top: 77.5%;*/
}
}
Javascript 解决方案
$( document ).ready(function() {
$('nav li:contains("Contact us")').addClass("active");
//get width and height of image in px
var imgWidth=$("#world-map").width();
var imgHeight=$("#world-map").height();
//console.log("image width x height ="+imgWidth+"x"+imgHeight);
//change icon position according to the percantage of where location is found
var sydneyLeft=0.815;
var sydneyTop=0.775;
//console.log("location left x top % ="+sydneyLeft+"x"+sydneyTop);
var sydneyLeftpx=0.815*imgWidth;
var sydneyToppx=0.775*imgHeight;
//console.log("location left x top px ="+sydneyLeftpx+"x"+sydneyToppx);
sydneyLeftpx=toInt(sydneyLeftpx);
sydneyLeftpx=sydneyLeftpx-6; //location-pinwidth
sydneyToppx=toInt(sydneyToppx);
sydneyToppx=sydneyToppx-6; //location-pinheight
//alert("location left x top px ="+sydneyLeftpx+"x"+sydneyToppx);
$(".sydney").css({left: sydneyLeftpx+"px",
top: sydneyToppx+"px"
});
});
注意:我还没有为 javascript 代码添加屏幕大小调整功能,只是通过刷新浏览器窗口来测试代码。
有人可以解释一下为什么这些值没有被正确计算,我该如何解决这个问题?
【问题讨论】:
-
css 中的任何内容都没有高度,因此可能在图像加载之前完成计算。建议根据图片纵横比设置高度
-
@charlietfl 我不知道你是什么意思....我已经使用 jquery var imgHeight=$("#world-map").height();
-
但如果图像尚未加载,则它当时没有高度。 document.ready 在图像加载之前触发。但是您知道地图图像的纵横比,因此您可以检查父宽度并进行相应设置
-
对不起,你的意思是我应该只计算document.ready下的宽度,然后根据纵横比改变高度吗?如果未加载图像,我将如何计算宽度?
-
它会填满父母不是吗?因此可以检查宽度并用于设置高度
标签: jquery css html map responsive-design