编辑希望这更清楚。 :)
现在,当您向下滚动时,您会注意到粉红色div仅在接触视口顶部时出现。如何在视口中途接触时使其显示?
https://jsfiddle.net/1p751fz5/
// 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) {
// 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);
}
});
};
答案 0 :(得分:2)
这可以通过jquery来完成。这是一个小提琴:https://jsfiddle.net/s13gjnwt/16/
在滚动时,获取窗口高度,用户滚动的数量以及隐藏div的顶部位置。 (我设置了一个窗口高度的一半的偏移量,这样div就不会出现,直到它在视口中的50%之后)
JS
$(window).on('scroll', function(){
var scrollAmount = $(window).scrollTop();
var windowHeight = $(window).height();
var halfHeight = $(window).height() / 2;
var topOfHiddenDiv = $('.hidden-div').offset().top;
if(((scrollAmount + windowHeight) - halfHeight) >= topOfHiddenDiv && !$('.hidden-div').hasClass('show')) {
$('.hidden-div').addClass('show');
}
});
.content {
padding-top: 1000px;
}
.hidden-div {
background: lightblue;
color: @white;
padding: 30px;
opacity: 0;
transition: opacity 0.3s;
margin-bottom: 300px;
}
.hidden-div.show {
opacity: 1;
}
注意:确保向下滚动小提琴