我正在使用codepen.io,我正在创建一个条形图。 图表有比例:一个在左边,一个在右边。
问题在于我希望左侧的值文本右对齐。我无法使用CSS来做到这一点,我相信javascript可以完成这项工作。
以下是我用来绘制比例的两个函数,以及我项目的链接。
function drawScalesLeft(numOfScales)
{
console.log("Zeichne linke Skala mit " + numOfScales + " Einheiten");
for(i=0; i <= numOfScales ; i++)
{
var currentHeight = document.getElementById('bargraph').height;
var yPos = 279.75 * i / numOfScales + 10;
var marker = document.createElementNS(svgNS,"rect");
marker.setAttributeNS(null, 'x', 115);
marker.setAttributeNS(null, 'y', yPos);
marker.setAttributeNS(null, 'height', 0.2);
marker.setAttributeNS(null, 'width', 10);
document.getElementById("bargraph").appendChild(marker);
var markerText = document.createElementNS(svgNS,"text");
markerText.setAttributeNS(null, 'x', 50); //Textposition (horinzontal)
markerText.setAttributeNS(null, 'y', yPos+5);
markerText.textContent = (100-100 *i/ numOfScales).toFixed(digits) + " %";
document.getElementById("bargraph").appendChild(markerText);
}
}
function drawScalesRight(numOfScales)
{
console.log("Zeichne rechte Skala mit " + numOfScales + " Einheiten");
for(i=0; i <= numOfScales; i++)
{
var currentHeight = document.getElementById('bargraph').height;
var yPos = 279.75 * i / numOfScales + 10;
var marker = document.createElementNS(svgNS,"rect");
marker.setAttributeNS(null, 'x', 175);
marker.setAttributeNS(null, 'y', yPos);
marker.setAttributeNS(null, 'height', 0.2);
marker.setAttributeNS(null, 'width', 10);
document.getElementById("bargraph").appendChild(marker);
var markerText = document.createElementNS(svgNS,"text");
markerText.setAttributeNS(null, 'x', 195);//Textposition (horinzontal)
markerText.setAttributeNS(null, 'y', yPos+5);
markerText.textContent = (500-500 * i/ numOfScales).toFixed(digits2) + " m";
document.getElementById("bargraph").appendChild(markerText);
}
}
完整代码:
答案 0 :(得分:1)
您需要正确计算x
个节点的text
值。
看起来像这样的行55
之后
document.getElementById("bargraph").appendChild(markerText);
添加此
markerText.setAttributeNS(null, 'x', 100 - markerText.getBBox().width);
一切都应该是好的。
另外,删除第50
行
markerText.setAttributeNS(null, 'x', 50); //Textposition (horinzontal)