My task involves adding annotations to specific spans of text. Below is the code snippet:
HTML
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="css/demo.css" />
<script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="js/demo.js"></script>
</head>
<body>
<div class="dialog-container">
<div class="annotation-head"></div>
<div class="annotation-segment">
<span class="marker" data-anno-id="0">This is a</span>
<span class="marker" data-anno-id="1">sample</span>
text
<span class="marker" data-anno-id="2">another one</span>
text
<span class="marker" data-anno-id="3">one mooooorreee</span>
</div>
</div>
</body>
</html>
Javascript
String.prototype.width = function(font) {
var f = font || '12px arial',
o = $('<div>' + this + '</div>')
.css({'position': 'absolute', 'float': 'left', 'white-space': 'nowrap', 'visibility': 'hidden', 'font': f})
.appendTo($('body')),
w = o.width();
o.remove();
return w;
}
$(document).ready(function() {
var annos = ['first', 'second', 'third', 'forth']; // annotation data
$('.marker').each(function () {
var $t = $(this),
pos = parseInt($t.attr('data-anno-id')),
annoStr = annos[pos];
// create an annotation for each marker
var top = this.offsetTop - 5,
left = this.offsetLeft + ($t.width() - annoStr.width())/2,
width = $t.width(),
style = 'style="top:' + top + 'px; left:' + left + 'px;"';
$('.annotation-head').append('<span class="anno label" ' + style + '>' + annoStr + '</span>');
});
});
CSS
.dialog-container {
width: 600px;
height: 200px;
border-style: solid;
border-width: 1px;
border-color: black;
border-radius: 10px;
padding-left: 5px;
}
.annotation-head {
padding-top: 7px;
}
.annotation-segment, .annotation-head {
position: relative;
}
.marker {
background: lightgreen;
}
.anno {
position: relative;
text-align: center;
}
.label {
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
position: relative;
display: inline-block;
padding: 2px;
font-size: 11.844px;
font-weight: bold;
line-height: 14px;
color: #ffffff;
text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25);
white-space: nowrap;
vertical-align: baseline;
background-color: #999999;
}
I believe I'm close to achieving the desired outcome. However, due to using separate divs for annotations and text, the positioning of labels above the correct span is not consistent after the first annotation. Is there a way to calculate the accurate left offset for the labels without using
position: absolute?