Use*_*ame 4 javascript svg d3.js
下面是 HTML 页面内容的外观。
<!DOCTYPE html>
<html>
<head>
<script src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<object type="image/svg+xml" data="Map-edited.svg"></object>
<script src="script.js"></script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
这是script.js
外观。
var tooltip = d3.select("body")
.append("div")
.style("position", "absolute")
.style("z-index", "10")
.style("visibility", "hidden")
.text("Hello");
var svg= d3.select("object").select("svg");
svg.selectAll('g')
.on("mouseover",function(){
return tooltip.style("visibility","visible");
})
.on("mousemove",function(){
var offset= 20;
var topPosition= (event.pageY-offset)+"px";
var leftPosition= (event.pageX+offset)+"px";
return tooltip.style("top",topPosition).style("left",leftPosition);
})
.on("mouseout", function(){
return tooltip.style("visibility","hidden");
});
Run Code Online (Sandbox Code Playgroud)
当我打开 HTML 页面时,我看到了包含所有g
元素的 SVG 元素。当我将鼠标悬停在每个g
元素上时,不会出现任何工具提示。但是如果我object
用svg
标签及其内容替换,工具提示就起作用了。如何让 d3 在object
标签中选择一个 SVG ?
您需要访问<object>
contentDocument
才能访问其包含的元素。
为此,您还需要等到您<object>
加载了其内容。
我不太喜欢 d3,所以它可能不是最好的 d3 方式,但至少它有效:(
但不是在 StackSnippet 的 null 起源的 iframe 中......)
fetch('https://upload.wikimedia.org/wikipedia/commons/f/fd/Ghostscript_Tiger.svg')
.then(r => r.blob())
.then(b => obj.data = URL.createObjectURL(b));
obj.onload = function() { // wait for the svg has loaded
var tooltip = d3.select("body")
.append("div")
.style("position", "absolute")
.style("z-index", "10")
.style("visibility", "hidden")
.text("Hello");
var obj = this; // we're in the object's load event handler.
var svg = d3.select(obj.contentDocument) // get the contentDocument
.select("svg"); // then get the svg inside
svg.selectAll('g')
.on("mouseover", function() {
return tooltip.style("visibility", "visible");
})
.on("mousemove", function() {
var event = d3.event;
var offset = 20;
var topPosition = (event.pageY - offset) + "px";
var leftPosition = (event.pageX + offset) + "px";
return tooltip.style("top", topPosition).style("left", leftPosition);
})
.on("mouseout", function() {
return tooltip.style("visibility", "hidden");
});
};
Run Code Online (Sandbox Code Playgroud)
<script src="https://d3js.org/d3.v4.min.js"></script>
<object id="obj" type="image/svg+xml"></object>
Run Code Online (Sandbox Code Playgroud)