每次有人将鼠标悬停在某个按钮上时,我都可以登录到控制台,但是我怎么能在这个问题上花多少秒并汇总总数呢?
var result = document.getElementById('result');
var source = Rx.Observable.fromEvent(result, 'mouseover');
var subscription = source.subscribe(
function (x) {
console.log('Hovered!');
}
);
答案 0 :(得分:1)
如果我正确理解您的要求,您需要检查鼠标何时也离开元素,然后使用和scan
之类的运算符来总和。一个相对简单的方法是获取mouseover
的时间戳,然后在mouseout
事件上进行采样:
var result = document.getElementById('result');
var mouseOver = Rx.Observable.fromEvent(result, 'mouseover');
var mouseOut = Rx.Observable.fromEvent(result, 'mouseout');
mouseOver
//Get the time of the mouseover event
.timestamp()
//Don't emit until the mouseOut triggers
.sample(mouseOut)
//Extract only the timestamp value
.pluck('timestamp')
//Get a new timestamp (remember this is *after* mouse out)
.timestamp()
//Compute the timeinterval
.map(x => x.timestamp - x.value)
//Add the new time interval to the running total
.scan((total, diff) => total += diff, 0)
.subscribe(x => console.log(x));
答案 1 :(得分:0)
这是我提出的另一种解决方案,不是最佳的,但值得分享该技术。
var counter = 0;
var source = Rx.Observable.interval(100)
.map(() => '.');
var display = document.querySelector("#display");
var toggle = document.querySelector("#toggle");
var hover = false;
var mouseOver = Rx.Observable.fromEvent(toggle, "mouseenter")
.map(e => {hover=true;});
var mouseOut = Rx.Observable.fromEvent(toggle, "mouseleave")
.map(e => {hover=false;});
mouseOver //.filter(x => true)
.flatMapLatest(() => source.takeUntil(mouseOut))
.subscribe(x => {counter += 1; display.innerText = counter});