页面停止滚动时触发功能

时间:2010-08-24 09:17:03

标签: javascript jquery javascript-events

如何在浏览器窗口停止滚动时触发功能?通过鼠标滚轮,单击,空格键或箭头键?这样的行动有什么事吗?我曾尝试在线搜索但无法获得任何解决方案。我对jQuery解决方案很好。

2 个答案:

答案 0 :(得分:11)

没有“事件”,但你可以自己制作,如下:

$(function() {
  var timer;
  $(window).scroll(function() {
    clearTimeout(timer);
    timer = setTimeout(function() {
      $(window).trigger("scrollStop");
    }, 250);
  });
});

然后你可以绑定它,就像这样:

$(window).bind("scrollStop", function() {
  alert("No one has scrolled me in 250ms, where's the love?");
});

这会创建一个事件,对此没有“停止”,但您可以定义自己的......在这种情况下,“停止”定义为“未在250毫秒内滚动”,您可以将计时器调整为喜欢,但这就是主意。

另外,如果你只做一件事就不需要事件,只需将你的代码放在我正在调用$(window).trigger("scrollStop")的地方,它就会在滚动停止后运行n毫秒。

答案 1 :(得分:0)

所选答案的非private SearchQuery defineSearch(String topic, List<String> areas) { MultiMatchQueryBuilder multiMatchQueryBuilder = new MultiMatchQueryBuilder(topic) .operator(Operator.OR) .minimumShouldMatch("50%") .fuzziness(Fuzziness.ONE) .prefixLength(1) .type(MultiMatchQueryBuilder.Type.MOST_FIELDS); BoolQueryBuilder searchQuery = boolQuery() .must(multiMatchQueryBuilder); // if (!areas.isEmpty()) { // BoolQueryBuilder valuesFilter = boolQuery(); // // for (String value : areas) { // QueryBuilder valueFilter = QueryBuilders.termQuery("areas", value); // valuesFilter.must(valueFilter); // } // searchQuery.must(valuesFilter); // } return new NativeSearchQueryBuilder() .withQuery(searchQuery) .withFilter(boolQuery().must(termQuery("areas", areas))) .build(); } Javascript版本:

jQuery
var elem = document.getElementById('test');

(() => {
  var onScrollStop = (evt) => {
    // you have scroll event as evt (for any additional info)
    var scrollStopEvt = new CustomEvent('scrolling-stopped', {detail: 'foobar stopped :)'});
    elem.dispatchEvent(scrollStopEvt);
  }
  var scrollStopLag = 300 // the duration to wait before onScrollStop is triggerred.
  var timerID = 0;
  const handleScroll = (evt) => {
    clearInterval(timerID);
    timerID = setTimeout(
      () => onScrollStop(evt),
      scrollStopLag
    )
  }
  elem.addEventListener('scroll', handleScroll);
})()

elem.addEventListener(
  'scrolling-stopped', 
  (evt) => console.log(evt.detail)
)
#test {
  height: 300px;
  width: 300px;
  overflow: auto;
}

#test #test-inner {
  height: 3000px;
  background: linear-gradient(lightseagreen 0%, lightyellow 40%, lightcoral 100%);
}

祝你好运...

P.S。我是<div id="test"> <div id="test-inner"></div> </div> BIG 粉丝:)