什么时候
“使用严格”;
对我的 D3JS 力网络图有效,我无法使用 this.getBBox();
使用以下代码在力网络图中旋转边缘标签文本:
edgelabels.attr('transform',function(d,i){
if (d.target.x<d.source.x){
bbox = this.getBBox();
rx = bbox.x+bbox.width/2;
ry = bbox.y+bbox.height/2;
return 'rotate(180 '+rx+' '+ry+')';
}
else { return 'rotate(0)'; }
});
如果我禁用 "use strict;"
,我的代码运行时不会出现错误,并且标签会正确旋转。 fiddle :
https://jsfiddle.net/NovasTaylor/cnaqaxnh/
我的原始代码基于此 block : http://bl.ocks.org/jhb/5955887
如何将我的代码固定为使用 "use strict;"
与 getBBox() 或 getBBox() 的替代方法一起运行?
最佳答案
这里的问题不是getBBox()
,而是缺少var
:在非严格模式下,对未声明变量的赋值会认为该变量是全局变量.但是,这在严格模式下不起作用。
如果您查看 MDN page关于严格模式:
First, strict mode makes it impossible to accidentally create global variables. In normal JavaScript mistyping a variable in an assignment creates a new property on the global object and continues to "work" (although future failure is possible: likely, in modern JavaScript). Assignments which would accidentally create global variables instead throw in strict mode. (emphasis mine)
所以,而不是:
edgelabels.attr('transform', function(d, i) {
if (d.target.x < d.source.x) {
bbox = this.getBBox();
rx = bbox.x + bbox.width / 2;
ry = bbox.y + bbox.height / 2;
return 'rotate(180 ' + rx + ' ' + ry + ')';
} else {
return 'rotate(0)';
}
});
应该是:
edgelabels.attr('transform', function(d, i) {
if (d.target.x < d.source.x) {
var bbox = this.getBBox();
var rx = bbox.x + bbox.width / 2;
var ry = bbox.y + bbox.height / 2;
return 'rotate(180 ' + rx + ' ' + ry + ')';
} else {
return 'rotate(0)';
}
});
这是更新后的 fiddle :https://jsfiddle.net/onnoqyp4/
关于javascript - "use strict"时getBBox错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47763791/