D3.js中的d3.selection.on()函數用於將特定的事件偵聽器添加到元素。事件可以是事件類型為click,mouseover等的字符串。
用法:
selection.on(typenames[, listener[, options]])
參數:此函數接受上述和以下描述的兩個參數:
- Typename Listener:這是一個字符串事件類型,例如單擊,提交等。
- Options:這是一個可選對象,可以說明偵聽器的特殊特征。
注意:如果未指定偵聽器,則它將返回特定元素的當前分配事件。
返回值:此函數返回對象。
以下示例說明了JavaScript中的D3.js selection.on()函數:
範例1:
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta
name="viewport"
path1tent="width=device-width,
initial-scale=1.0"/>
<title>D3.js selection.on() Function</title>
</head>
<style>
li {
background-color:green;
color:#ffffff;
width:50px;
margin-bottom:5px;
padding:20px;
height:40px;
}
li:hover {
cursor:pointer;
opacity:0.8;
}
</style>
<body>
<ul>
<li>Geeks for geeks</li>
<li>GEEKS FOR GEEKS</li>
</ul>
<script src=
"https://d3js.org/d3.v4.min.js">
</script>
<script src=
"https://d3js.org/d3-selection.v1.min.js">
</script>
<script>
let li = d3.select("li");
let x = li.on("click", () => {
console.log("Clicked");
});
</script>
</body>
</html>
輸出:
在點擊框之前:
單擊框後:
範例2:
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta
name="viewport"
path1tent="width=device-width,
initial-scale=1.0"/>
<title>D3.js selection.on() Function</title>
</head>
<style>
li {
background-color:green;
color:#ffffff;
width:100px;
margin-bottom:5px;
padding:20px;
height:50px;
}
li:hover {
cursor:pointer;
opacity:0.8;
}
</style>
<body>
<ul>
<li>Geeks for geeks</li>
</ul>
<script src=
"https://d3js.org/d3.v4.min.js">
</script>
<script src=
"https://d3js.org/d3-selection.v1.min.js">
</script>
<script>
let li = d3.select("li");
let x = li.on("mouseover", () => {
let li = document.querySelector("li");
li.innerHTML = "mouseOver event";
});
// When cursor moves out of the li tag
x = li.on("mouseout", () => {
let li = document.querySelector("li");
li.innerHTML = "Geeks for geeks";
});
</script>
</body>
</html>
輸出:
鼠標懸停時:
移出鼠標時:
相關用法
- PHP imagecreatetruecolor()用法及代碼示例
- p5.js year()用法及代碼示例
- d3.js d3.utcTuesdays()用法及代碼示例
- PHP ImagickDraw getTextAlignment()用法及代碼示例
- PHP Ds\Sequence last()用法及代碼示例
- PHP array_udiff_uassoc()用法及代碼示例
- PHP geoip_continent_code_by_name()用法及代碼示例
- d3.js d3.map.set()用法及代碼示例
- PHP GmagickPixel setcolor()用法及代碼示例
- PHP opendir()用法及代碼示例
- PHP cal_to_jd()用法及代碼示例
- d3.js d3.bisectLeft()用法及代碼示例
- PHP stream_get_transports()用法及代碼示例
- PHP Ds\Deque pop()用法及代碼示例
注:本文由純淨天空篩選整理自tarun007大神的英文原創作品 D3.js selection.on() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。