[英]jQuery image height change on scroll
我的網站上有固定的標題,我嘗試在向下滾動到特定點時調整徽標圖像的大小,然后在向上滾動時增大徽標圖像的大小。 向下滾動時,圖像達到原始高度的一半時將不再變小。 這是我嘗試過的,但是沒有用。 謝謝。
jQuery(window).scroll(function() {
var windowScroll = jQuery(window).scrollTop(),
imageHeight = jQuery('.headlogo').css('height'),
marginHeight = jQuery('.nav.navbar').css('margin-top'),
newMargin = marginHeight - windowScroll,
newHeight = imageHeight - windowScroll,
stopHeight = imageHeight / 2;
jQuery('.headlogo').css("height", newHeight);
jQuery('nav.navbar').css("margin-top", newMargin);
if(newHeight == stopHeight){
jQuery('.headlogo').css("height", stopHeight);
}
});
好吧,只是為了從這個問題中取樂,考慮一下
size = Math.PI/2/1000
height(x) = maxHeight/2( 1 + Math.cos(x/size))
因此,當scroll為0時,它將僅為maxHeight,而當x為1000時,它將僅為maxHeight / 2,並且在2000時再次為maxHeight,依此類推。
function imgSize(maxHeight, cycle) {
var s = Math.PI/2/cycle
return function(x) { return maxHeight/2(1 + Math.cos(x/s) }
}
var img = $('img.headlogo')
, maxHeight = img.css('height')
, resize = imgSize(maxHeight, 1000)
$(window).on('scroll', function(e) {
var x = $(document).scrollTop()
img.stop().animate({ height: resize(x) }, 500)
})
如果需要數字屬性,則必須使用:
imageHeight = $('.headlogo').height();
否則,您的imageHeight
為NaN
並且您不能使用:
newHeight = imageHeight - windowScroll
您需要像這樣的滾動事件之外獲取imageHeight和marginHeight
//get original height and margin-top outside scroll
var imageHeight = parseInt($('.headlogo').css('height')),
stopHeight=imageHeight / 2,
marginHeight = parseInt($('.navbar').css('margin-top'))
stopMargin=marginHeight/2;
$(window).scroll(function(e) {
var windowScroll = $(window).scrollTop(),
newMargin = marginHeight - windowScroll,
newHeight = imageHeight - windowScroll;
if(newHeight>=stopHeight){
$('.headlogo').css("height", newHeight);
$('.navbar').css("margin-top", newMargin);
}
else{
$('.headlogo').css("height", stopHeight);//if it scroll more set to stopHeight
//you can also set $('.navbar').css("margin-top", stopMargin);
}
});
這樣的JS小提琴在滾動時會更改css類,因此您可以將一個類的圖像設置為100%,將其設置為50%,因此在滾動時,JS會將CSS類更改為您想要的大小。喜歡。
$(function(){
var images = $(‘.yourClass’)
scrolledDistance = $(document).scrollTop()
windowHeight = $(window).height()
inView = scrolldDistance + windowHeight
$(images).each(function(){
var position = $(‘this’).position()
topOffset = position.top
if (inView < = topOffset ){
$(this).css({‘opacity’:’0′})
}
})
$(window).scroll(function () {
//update scrolled distance
scrolledDistance = $(document).scrollTop()
$(images).each(function(){
var position = $(‘this’).position()
topOffset = position.top
if (inView < = topOffset ){
$(this).animate({‘opacity’:’0′},500)
}
})
})
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.