为什么replaceWith()不像css()那样触发?

Why does replaceWith() not trigger the same way as css()?

本文关键字:css replaceWith 不像 为什么      更新时间:2023-09-26

我试图触发一个固定的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>"
        );
    }
[...]

这只适用于当你的窗口在加载时滚动到该点或以下,即使窗口。很明显,pageYOffset会随着滚动而不断变化。

但是这个例子,使用css(),它应该改变。

if(y_scroll_pos > img_position.top) {
        $(".fixed").css(
            "background-color","red";
        );
    }
    else {
        $(".fixed").css(
            "background-color","yellow";
        );
    }
[...]

为什么?这两种方法有什么区别?

当您只能更改所需的内容时,为什么要更改整个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"});
    }
});