簡體   English   中英

如何在d3.js中取消鼠標懸停過渡

[英]How to cancel the mouseover transition in d3.js

這是我的HTML的結構

svg
   g id=invisibleG
     g
       circle
     g
       circle
     g
       circle

所以我想在任何特定的圓圈上懸停這樣的東西

svg
       g id=invisibleG
         g
           circle --> radius is increased on hover.....decreased on hoverout
           text
         g
           circle
         g
           circle

這是代碼

 .on("mouseover",function(){
     var r=d3.select(this).attr("r");
     d3.select(this).style('fill','tan')
                    .style('fill-opacity', '1')
                    .transition()
                    .duration(1000)
                    .attr("r",50);
     d3.select(this).attr("stroke","blue")
                    .attr("stroke-width",4);

 })

 .on("mouseout",function(){
     var r=d3.select(this).attr("prevRadius");
     d3.select(this).attr("r",r)
                    .attr("stroke-width",0)
                    .style('fill-opacity','0');

 });

現在的問題是,當我將鼠標懸停在一個圓上並立即懸停在其上時,在mouseover中開始的過渡不會立即停止,它完成了過渡並且半徑大小增大了,盡管事實上應該將mouseout事件設置為無論發生什么轉變,都應停止。 請讓我知道問題及其解決方案。

在這兩種情況下,您只需要使用過渡即可。 文檔中

如果較新的過渡在給定元素上運行,它將隱式取消任何較舊的過渡,包括已計划但尚未運行的過渡。 這允許新的過渡(例如響應新用戶事件的過渡)取代較舊的過渡,即使這些較舊的過渡已階段化或具有交錯的延遲。

因此,您的代碼將需要像這樣。

.on("mouseover", function() {
    this.prevRadius = d3.select(this).attr("r");
    d3.select(this)
        .style('fill','tan')
        .style('fill-opacity', '1')
        .transition()
        .duration(1000)
        .attr("r",50)
    d3.select(this)
        .attr("stroke","blue")
        .attr("stroke-width",4);

}).on("mouseout", function() {

    d3.select(this)
        .transition()
        .attr("r", this.prevRadius)
        .attr("stroke-width",0)
        .style('fill-opacity','0');
});

演示在這里

如果您的d3版本足夠成熟(3.3+),那么他們似乎已經添加了選擇。 打斷

因此,您可以嘗試:

.on("mouseout",function(){
    d3.select(this).interrupt();
    // if interrupt isn't supported in your version use below
    //d3.select(this).transition().duration(0);
})

否則, 相同選擇上的新過渡將取消舊的活動過渡 因此,您可以在mouseout上運行新的過渡,然后再次過渡到重置值。 如果您只想凍結過渡,只需運行一個虛擬過渡即可取消舊過渡。

進一步了解

如果您的目標是停止死角中r (半徑)的唯一過渡,請參閱此使用中斷的小提琴

如果您的目標是重置r值或鼠標懸停時所做的非轉換更改,請參閱此小提琴

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM