Javascript 将函数用作“函数”;关于;事件
我目前拥有以下功能:Javascript 将函数用作“函数”;关于;事件,javascript,jquery,Javascript,Jquery,我目前拥有以下功能: function highlightBoxes() { var windowStart = $(window).scrollTop(); var windowEnd = windowStart + $(window).height(); $('.box').each(function() { var box = $(this); var start = box.offset().top; var end = start + box.he
function highlightBoxes() {
var windowStart = $(window).scrollTop();
var windowEnd = windowStart + $(window).height();
$('.box').each(function() {
var box = $(this);
var start = box.offset().top;
var end = start + box.height();
if (windowStart <= start && windowEnd >= end) {
box.addClass('active');
} else {
box.removeClass('active');
}
});
}
highlightBoxes();
$(document).scroll(highlightBoxes);
$(window).resize(highlightBoxes);
如何实现这一点?在上使用
意味着您将需要触发一个同名事件,一个超级简单的版本是使用文档
作为消息总线,如:
$(document).trigger('inview');
因此,在您的代码中确定inview
应该为true的那一点上,触发一个如上所述的事件,此时on
事件将运行该函数
根据上面的代码,您可能希望将if
语句移出on
事件,并将其作为单独的函数运行。当elementIsInView
返回true时,您可以触发inview
事件。您可以使用悬停事件
$(document).on('hover','.box', function () {
if (elementIsInView) {
// make the box red
} else {
// make the box the original color
}
});
如果我不清楚你的答案,请告诉我 单击、悬停、拖动都是事件。事件是一个操作,由用户应用。函数是使用javascript声明的。未直接运行。它仅在事件触发器之后运行。事件由w3c声明
我想你需要这样的东西:
通过按钮点击分配函数。它从按钮点击事件开始工作
$('button')。在('click',hello')上
函数hello(){
console.log('单击按钮')
}
嗨
试试这个:
function checkElementToBeInView(elem, callback) {
$(elem).each(function() {
var element = $(this);
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();
var elemTop = element.offset().top;
var elemBottom = elemTop + element.height();
var isInView = ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
callback(element, isInView);
});
}
$(window).on("load resize scroll", function(e) {
checkElementToBeInView(".box", function(elem, isInView) {
if (isInView)
elem.addClass('active');
else
elem.removeClass('active');
});
函数checkElementToBeInView(元素,回调){
$(元素)。每个(函数(){
var元素=$(此);
var docViewTop=$(window.scrollTop();
var docViewBottom=docViewTop+$(window).height();
var elemTop=element.offset().top;
var elemBottom=elemTop+element.height();
变量isInView=((elemBottom=docViewTop));
回调(元素,isInView);
});
}
$(窗口)。打开(“加载调整大小滚动”,功能(e){
选中ElementToBeInView(“.box”,函数(elem,isInView){
如果(isInView)
元素addClass(“活动”);
其他的
元素移除类(“活动”);
});
是的,这根本不是我想要做的。请问你还想实现什么?我不确定这对我有什么帮助。:/。
function checkElementToBeInView(elem, callback) {
$(elem).each(function() {
var element = $(this);
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();
var elemTop = element.offset().top;
var elemBottom = elemTop + element.height();
var isInView = ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
callback(element, isInView);
});
}
$(window).on("load resize scroll", function(e) {
checkElementToBeInView(".box", function(elem, isInView) {
if (isInView)
elem.addClass('active');
else
elem.removeClass('active');
});