我正在显示用户位置的地图,然后在地图上显示一条消息。我想基于用户的设备& amp;动态调整地图大小(mapWidth& mapHeight)。窗口大小和文本在中心的位置。
我使用50%的上/下定位,但通常文字不是中心定位。
var ip = '1.2.3.4';
var msg = 'Welcome User';
var mapUrl = 'https://maps.googleapis.com/maps/api/staticmap?center=';
var mapWidth = 250;
var mapHeight = 150;
var mapParams = '&zoom=9&size='+mapWidth+'x'+mapHeight+'&scale=1';
var locationUrl = 'https://ipapi.co/';
var locationField = '/latlong/';
var updateMap = function(data){
$('.map-img').attr('src', mapUrl + data + mapParams);
$('.ip').text(msg).fadeIn('slow');
};
$.get(locationUrl + ip + locationField, updateMap);

.ip {
position: absolute;
top: 50%;
left: 50%;
display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="position:relative;">
<img class="map-img" src="">
<div class="ip"></div>
</div>
&#13;
答案 0 :(得分:1)
问题是因为包含div
涵盖了整个页面宽度。您应该将其设置为display: inline-block
。最好使内部div
覆盖其容器的整个宽度,并使用text-align: center
而不是left: 50%
,否则您必须手动计算文本的宽度并减去一半用于集中文本的那个值。试试这个:
var ip = '1.2.3.4';
var msg = 'Welcome User';
var mapUrl = 'https://maps.googleapis.com/maps/api/staticmap?center=';
var mapWidth = 250;
var mapHeight = 150;
var mapParams = '&zoom=9&size=' + mapWidth + 'x' + mapHeight + '&scale=1';
var locationUrl = 'https://ipapi.co/';
var locationField = '/latlong/';
var updateMap = function(data) {
$('.map-img').attr('src', mapUrl + data + mapParams);
$('.ip').text(msg).fadeIn('slow');
};
$.get(locationUrl + ip + locationField, updateMap);
&#13;
.container {
display: inline-block;
position: relative;
}
.ip {
position: absolute;
top: 50%;
left: 0;
right: 0;
bottom: 0;
text-align: center;
display: none;
margin-top: -0.5em;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<img class="map-img" src="">
<div class="ip"></div>
</div>
&#13;
答案 1 :(得分:0)
使用
.ip {
position: absolute;
top: 50%;
left: 50%;
display: none;
transform: translate(-50%, -50%);
}