通过jquery获取图像中心的文本

时间:2012-02-24 08:25:31

标签: jquery html

场景是我想在图像上插入一个放在<div>中的数字(图像的z-index = -1)。我的锚标签内有一个图像。我已经找到了锚标记的顶部和左侧位置(id = PersonalInfo),然后我将<div>的位置设置为适合图像的中心。但是数字显示在某个位置浏览器窗口的极右侧,以及图像下方的一点。如何将其置于适当的位置。 另外,我想知道如何获取与浏览器窗口边界相关的任何元素的顶部和左侧坐标(不包括顶部的工具栏)。

 <a href='#' id='PersonalInfo' class='links' disabled='disabled' name='1' ><img src='../Images/COBreadCrumb/disabled.gif'></a>

The Jquery code I wrote for it is this:

var number = $("#PersonalInfo").attr("name");
          var tag1 = "<font style='Verdana' size='3'>";
          var tag2 = "</font>";
          var content = tag1 + number + tag2;
          $("#" + number).html(content);
          var LinkTop = $("#PersonalInfo").offset().top;
          var LinkHeight = $("#PersonalInfo").height();
          var NumberTop = LinkTop + (LinkHeight / 2);
          var NumberLeft = $("#PersonalInfo").offset().left + ($("#PersonalInfo").width() / 2);
          $("#" + number).offset({top:NumberTop,left:NumberLeft});

 The div tag:

<div id="1"></div> 

3 个答案:

答案 0 :(得分:2)

不需要jQuery ..

a {
    background: url(http://www.google.nl/images/srpr/logo3w.png);
    height: 95px;
    width: 275px;
    display: table-cell;
    vertical-align: middle;
    text-align: center;

}​

http://jsfiddle.net/9dtCj/

此示例显示如何将文本放置在图像的中间。

答案 1 :(得分:1)

理查德击败了我,正如bazmegakapa指出的那样,IE7中的表格细节失败了,这是另一个解决方案:

<!doctype html>
<html>
<head>
<title>Center</title>
<style>
#meme {
  background: url(http://thechive.files.wordpress.com/2010/12/funny-cat-faces-8.jpg?w=500&h=374);

  /* same size as background image */
  width: 500px;
  height: 374px;

  /* #meme-text will be positioned relative to this */
  position: relative;
}

#meme-text {
  /* The height of this element will be approximate 60px too,
   * assuming the content will fit on one line.
   */
  font-size: 60px;

  /* Center vertically <- This is the tricky part. */
  position: absolute;
  top: 157px;  /* #meme height / 2 - height of this element */

  /* Center horizontally */
  text-align: center;
  width: 100%;

  /* Make this example look pretty. */
  color: white;
  font-family: Impact, sans-serif;
}
</style>
</head>
<body>

<div id="meme">
  <div id="meme-text">I NOM YOUR FACE</div>
</div>

</body>
</html>

答案 2 :(得分:0)

这是一个解决方案:

<!doctype html>
<html>
<head>
<title>Center</title>
<style>
#meme {
  background: url(http://thechive.files.wordpress.com/2010/12/funny-cat-faces-8.jpg?w=500&h=374);

  /* same size as background image */
  width: 500px;
  height: 374px;

  text-align: center;
  vertical-align: middle;

  /* You need this to make vertical-align work the way you want it to. */
  display: table-cell;

  /* Make this example look pretty. */
  color: white;
  font-size: 48pt;
  font-family: Impact, sans-serif;
}
</style>
</head>
<body>

<div id="meme">
  I NOM YOUR FACE
</div>

</body>
</html>