怎样才能让它从顶部偏移50%?我还尝试添加 - ($window.height()/2)
我可以设置像素距离 $(this).offset().top - 800)
但我想使用百分比。 50% 是任意的,也可以是 25%,等等。
如果想知道的话,这里是完整的脚本:
// constants
var BTN_CLS = 'owl-thumb-item',
BTN_ANIMATION_MILLIS = 200,
DIV_ANIMATION_MILLIS = 1000;
// document ready handler
$(document).ready(function() {
// display buttons from first 'div'
showBtns('one', BTN_CLS);
// window scroll handler
$(window).scroll(function() {
$('.hidden').each(function(i, v) {
if ($(window).scrollTop() > $(this).offset().top - 800) {
// show 'div' when scrolling
showDiv($(this), onCompleteDivAnimation($(this)));
}
});
});
});
/**
* Used to show an animated 'div' and perform some actions.
* @param {Function} completeCallback Action performed after animation.
* @param {Object} div Target element.
*/
function showDiv(div, completeCallback) {
// check if 'div' is currently animated and avoid animation queue
if (!div.is(':animated')) {
div.animate({
opacity: 1
}, {
complete: completeCallback,
duration: DIV_ANIMATION_MILLIS
});
}
};
/**
* Used to perform actions after completing a 'div' animation.
*/
function onCompleteDivAnimation(div) {
showBtns(div.prop('id'), BTN_CLS);
};
/**
* Used to show button(s) from a 'div' element.
* @param {String} divId Target element Id.
* @param {String} btnCls Button(s) CSS class.
*/
function showBtns(divId, btnCls) {
var btnGroup = getBtnGroup(divId, btnCls);
animateBtn(btnGroup);
};
/**
* Used for creating a group of button(s) from a 'div' element.
* @param {String} divId Target element Id.
* @param {String} btnCls Button(s) CSS class.
* @returns {Array} btnGroup
*/
function getBtnGroup(divId, btnCls) {
var domBtns = $('#' + divId + ' .' + btnCls),
btnGroup = [];
for (var i = 0; i < (domBtns || []).length; ++i) {
btnGroup.push(domBtns[i]);
}
return btnGroup;
};
/**
* Used to animate a button group that normally comes from a 'div' element.
*/
function animateBtn(btnGroup) {
btnGroup = btnGroup || [];
$(btnGroup.shift()).fadeIn(BTN_ANIMATION_MILLIS, function() {
if (btnGroup.length > 0) {
animateBtn(btnGroup);
}
});
};
最佳答案
我认为您与部门运算符(operator)的关系是正确的。这对我有用:
$(window).on("scroll", function(){
var halfHeight = $(window).height() / 2;
if ($(window).scrollTop() > halfHeight) {
alert("Window has reached 50%");
}
});
你可以将其更改为 $(window).scroll(function()
我刚刚在下面的 fiddle 演示中使用了滚动。
这是一个工作 fiddle Fiddle
关于javascript - Offset ().top - 距顶部 50%?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35142809/