我在d3中有一条时间表,该时间表正在使用Wordpress中以JSON格式格式化的帖子中的数据。时间轴上的项目具有工具提示,其中显示了一些内容,包括项目的开始时间和结束时间。时间轴和工具提示都工作正常,除了我有两个条件可以更改工具提示中显示的内容,而且一次只能工作一个。
这两个条件是:
因此,我有三种单独的日期格式(都可以正常工作):
var displayDate = d3.time.format("%d %b %Y");
var displayMonthYear = d3.time.format("%b %Y");
var displayYear = d3.time.format("%Y");
而且我可以使用第一个条件将html附加到工具提示中:
var tip = d3.tip()
.attr('class', 'd3-tip')
.offset(function(d) { if (xTimeline(d.endDate) > 800) { return [-10, 8] } else { return [-10, -8] } })
.html(function(d) {
if ((xTimeline(d.endDate) - xTimeline(d.startDate) == 0)) {
return d.title + "<br/><p>" + displayDate(d.startDate) + "</p>" + d.content; }
else {
return d.title + "<br/><p>" + displayDate(d.startDate) + " to " + displayDate(d.endDate) + "</p>" + d.content; }
});
或第二个:
var tip = d3.tip()
.attr('class', 'd3-tip')
.offset(function(d) { if (xTimeline(d.endDate) > 800) { return [-10, 8] } else { return [-10, -8] } })
.html(function(d) { if (d.dateFormat == "Year only") {
return d.title + "<br/><p>" + displayYear(d.startDate) + "</p>" + d.content;
}
else if (d.dateFormat == "Month and year") {
return d.title + "<br/><p>" + displayMonthYear(d.startDate) + "</p>" + d.content;
}
else {
return d.title + "<br/><p>" + displayDate(d.startDate) + "</p>" + d.content;
}
});
但是我缺乏将它们结合起来的技能。我试图将第二个变量制成var或函数,但似乎无法使其正常工作。
我怀疑这对于一个精通Javascript的人来说真的很简单,但是现阶段还不是我。
任何帮助是极大的赞赏。
@tgerard:在重新阅读您的问题并意识到我没有提供您的要求后,我删除了之前的答案。我认为以下代码是您真正想要的:
var tip = d3.tip()
.attr('class', 'd3-tip')
.offset(function(d) {
if (xTimeline(d.endDate) > 800) {
return [-10, 8];
} else {
return [-10, -8];
}
})
.html(function(d) {
var toolTipContent = "";
if ((xTimeline(d.endDate) - xTimeline(d.startDate) == 0)) {
toolTipContent = getToolTipContent(d, true);
} else {
toolTipContent = getToolTipContent(d, false);
}
return toolTipContent;
});
function getToolTipContent(d, sameDates) {
var toolTipContent = d.title + "<br/><p>";
if (d.dateFormat == "Year only") {
toolTipContent += (sameDates)
? displayYear(d.startDate)
: displayYear(d.startDate) + " to " + displayYear(d.endDate);
} else if (d.dateFormat == "Month and year") {
toolTipContent += (sameDates)
? displayMonthYear(d.startDate)
: displayMonthYear(d.startDate) + " to " + displayMonthYear(d.endDate);
} else {
toolTipContent += (sameDates)
? displayDate(d.startDate)
: displayDate(d.startDate) + " to " + displayDate(d.endDate);
}
toolTipContent += "</p>" + d.content;
return toolTipContent;
}
在getToolTipContent函数中,我们检查日期格式的三个条件:
然后,对于这些条件中的每一个,我们使用三元运算符来确定要附加到toolTipContent字符串的内容。因此,如果'sameDates'计算为true,则'?'之后的部分。被附加。如果'sameDates'的计算结果为false,则会附加':'之后的部分。
祝您的项目好运!如果您对以上代码有任何疑问,请告诉我。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句