我正在显示用户位置的地图,然后在地图顶部显示一条消息。我想根据用户的设备和窗口大小动态调整地图大小(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>

最佳答案

问题是因为包含的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);

.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;
}

<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>

关于javascript - 文字不在图片上居中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37830884/

10-13 01:42