【发布时间】:2015-02-27 19:48:04
【问题描述】:
当尝试使用去抖动版本的 mousemove 事件处理程序时,d3.event 是 null。我想在这个去弹跳处理程序中使用d3.mouse 对象,但是d3.event 返回 null 并引发错误。如何在以下代码中访问d3.event:
// a simple debounce function
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) {
func.apply(context, args);
}
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) {
func.apply(context, args);
}
};
}
// the function to handle the mouse move
function handleMousemove ( context ) {
var mouse = d3.mouse( context );
console.log( mouse );
}
// create a debounced version
var debouncedHandleMousemove = debounce(handleMousemove, 250);
// set up the svg elements and call the debounced version on the mousemove event
d3.select('body')
.append('svg')
.append('g')
.append('rect')
.attr('width', 200)
.attr('height', 200)
.on('mousemove', function () {
debouncedHandleMousemove( this );
});
jsfiddle 如果您想看看它的实际效果。尝试将鼠标移动到 rect 元素上。
【问题讨论】:
标签: javascript d3.js svg dom-events