2014-02-27 42 views
0

一個小問題。 我有一個條形圖,我希望它在'mouseenter'行顯示一些文本。這工作正常,但我想刪除'mouseout'這個文本,我似乎無法得到它的竅門。刪除鼠標事件上的文本

非常感謝您的幫助! 附:d3.js腳本

d3.selectAll("div.line") 
     .append("div") 
     .attr("class","bar") 
     .style("width", function(d){return d.occurrence /10 + "px"}) 
     .on("mouseenter", function(d) { 
      d3.select(this) 
      .append("text") 
      .text(function(d){return d.occurrence + " occurences"}); 
     }) 
     .on("mouseout", function(d) { 
      d3.select(this) 
      .select(".text").remove(); 
     }); 
+0

可能是簡單的使用透明度。'風格( 「opacity」,1)'顯示文字,'style(「opacity」,0)'來隱藏它 – FernOfTheAndes

回答

1

在你代碼,您正試圖在mouseout上選擇.text。您正在選擇具有類的節點:「文本」而不​​是文本節點。刪除點。

我可能也會更改鼠標「選擇」,以「選擇」,以防萬一你錯過了一個鼠標事件,並無意中添加兩個文本節點。

編輯:

http://jsfiddle.net/QbGRE/

d3.select("div.line").selectAll("div.bar") 
    .data(data, function(d) { return d.id;  }) 
    .enter() 
    .append("div").attr("class","bar") 
    .style("width", function(d){return d.occurrence /10 + "px";}) 
    .on("mouseover", function(d) { 
     d3.select(this) 
     .append("text").style("pointer-events", "none") 
     .text(function(d){return d.occurrence + " occurences";}); 
    }) 
    .on("mouseout", function(d) { 
     d3.select(this) 
     .select("text").remove(); 
    }); 

盪滌你的代碼。

  1. 「鼠標懸停/鼠標移開」 而不是 「的mouseenter /鼠標移出」
  2. 。選擇( 「文本」),而不是 「的.text」。
  3. 風格上的文字(「指針事件」,「無),以阻止它導致額外的鼠標事件時,它的加入。
  4. 增加了假數據。
+0

感謝您的回答。 但沒有,它不能解決問題。文本字符串將自身添加到前一個沒有消失的文本字符串中... – basbabybel

+0

這只是問題的一部分。看我的編輯。 – Glenn

+0

完美的作品。我發現解決方案非常優雅。非常感謝,Glenn。 – basbabybel

0

要做到這一點最簡單的方法的有關部分是由一個唯一的ID分配給新的文本元素並選擇:

.on("mouseenter", function(d) { 
     d3.select(this) 
     .append("text") 
     .attr("id", "myText") 
     .text(function(d){return d.occurrence + " occurences"}); 
    }) 
    .on("mouseout", function(d) { 
     d3.select("#myText").remove(); 
    }); 
+0

這似乎有效,雖然我有點奇怪的閃爍,並且文字在某些時候不顯示,不知道什麼原因會導致這種奇怪的行爲? – basbabybel

+0

沒有一個完整的例子很難說,可能是因爲你將文本覆蓋到'div',並且鼠標暫時超過了text。這樣,'div'就會得到一個mouseout事件,而且HTML也沒有'text'元素 - 你是否想將它添加到SVG? –

+0

http://stackoverflow.com/questions/2802687/is-there-a-way-to-create-your-own-html-tag-in-html5。這是我在jsfiddle例子中遺漏的東西之一,但它仍然有效。 – Glenn