【 D3.js 入門系列 --- 8 】 對話操作(事件)

來源:互聯網
上載者:User

標籤:d3   event   on   click   mouseover   

    本人的個人部落格為: www.ourd3js.com 

    csdn部落格為: blog.csdn.net/lzhlzz 

    轉載請註明出處,謝謝。

    這一節介紹如何進行對話的操作,如按一下滑鼠,滑鼠滑過等。

    對一個被選擇的元素,添加對話操作,代碼如下:

.on("click", function(){} )
    函數可以是無名函數,也可以是自己定義的函數。上面代碼監聽的是按一下滑鼠的事件,但滑鼠在被選擇對象上單擊時,就會調用函數 function 。

    常用的事件(event)有:

  • click  : 點擊某元素時
  • mouseover  : 滑鼠移到某元素上
  • mouseout  : 滑鼠從某元素移開
  • mousemove : 滑鼠被移動
  • mousedown : 滑鼠按鍵被按下
  • mouseup : 滑鼠按鍵被鬆開
  • dblclick  :  滑鼠雙擊

    下面使用在5.1節中做的例子,為其中的直條圖添加對話操作。添加一部分代碼即可:
svg.selectAll("rect")   .data(dataset)   .enter()   .append("rect")   .attr("x", function(d,i){return 30 + xScale(i);   } )   .attr("y",function(d,i){return 50 + 500 - yScale(d) ;   })   .attr("width", function(d,i){return xScale.rangeBand();   })   .attr("height",yScale)   .attr("fill","red")   .on("click",function(d,i){d3.select(this)  .attr("fill","green");   })   .on("mouseover",function(d,i){d3.select(this)  .attr("fill","yellow");   })   .on("mouseout",function(d,i){d3.select(this)  .transition()          .duration(500)  .attr("fill","red");   });
    上面的代碼添加了滑鼠點擊( click ),滑鼠移入( mouseover ),滑鼠移出( mouseout )三個操作。
    上面的操作的函數中都調用了 d3.select(this) , 這是表示選擇當前的元素,this 是當前的元素,因為在事件中通常要改變被點擊的元素等,所以常有這段代碼,要記住。    另外,為了使得滑鼠移出元素時產生漸層效果,使用了 transition 和 duration ,詳細請看第6節。    如下:

    用滑鼠實際試試看吧,結果可見:  http://www.ourd3js.com/demo/event.html   ,完整的代碼可在瀏覽器中右鍵選擇欄中查看。


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.