当您滚动浏览图像顶部时,我正试图触发固定div内容的更改。
$(window).scroll(function() {
var y_scroll_pos = window.pageYOffset;
var img_position = $('img').position();
if(y_scroll_pos > img_position.top) {
$(".fixed").replaceWith(
"<p>Goodbye!</p>"
);
}
else {
$(".fixed").replaceWith(
"<p>Hello!</p>"
);
}
[...]
这仅适用于您的窗口在加载时滚动到该点或更低的位置,即使window.pageYOffset显然在滚动时不断变化。
但是这个例子,用css(),应该改变。
if(y_scroll_pos > img_position.top) {
$(".fixed").css(
"background-color","red";
);
}
else {
$(".fixed").css(
"background-color","yellow";
);
}
[...]
为什么呢?这两种方法有什么区别?
答案 0 :(得分:0)
为什么在只更改所需内容时完全更改HTML?
jQuery(function( $ ){ // (DOM is now ready)
var $img = $('img'); // Cache your elements outside of expensive
var $fixedP = $('.fixed').find("p"); // scroll events
$(window).scroll(function() {
var pastTop = window.pageYOffset > $img.position(); // Boolean value
$fixedP.text(pastTop ? "Goodbye!" : "Hello!" )
.css({background: pastTop ? "red" : "yellow"});
}
});