gpt4 book ai didi

javascript - 滚动时使用 jquery 传送一个 div

转载 作者:太空宇宙 更新时间:2023-11-04 09:40:52 25 4
gpt4 key购买 nike

我想知道是否可以在滚动时使用 jQuery 将 div“传送”到 DOM 的另一部分。

例如,假设我有一篇文章:

标题

Subt 1
Div area 1
Content 1

subt 是副标题,div area 是包含 div 的地方。

所以我需要达到这个结果:

当用户滚动时,div 会从一个区域跳到另一个区域

     **-- If I scroll from here --**

Subt 1
Div area 1
Content 1



Subt 2
Div area 2
Content 2



Subt 3
Div area 3
Content 3


**-- To here --**
Subt 4
Div area 4 -- The div will appear inside of here --
Content 4

我不希望 div 一次出现在所有地方,只是它会跟随滚动从一个区域移动到另一个区域。我什至不知道如何在谷歌中搜索这个,这就是我问的原因。

提前致谢

最佳答案

您要使用的方法是 jQuery 的 detach ( https://api.jquery.com/detach/ )

// Detach is to splice from the DOM
$SwappedElement = $('#HotSwapDiv').detach();
// substitute logic to determine div position by window scroll
$DestinationDivArea = $('#div_identifier)
// Append (attach to end) of Destination div
$DestinationDivArea.append( $SwappedElement );

您可以在 jQuery 中使用以下方法监听窗口滚动事件:

$(window).scroll(function() {
// Get current window scroll amount in pixels
iPixelsScrolledFromTop = $(window).scrollTop();
// Get the amount from the top of one of your divs
iDivAreaPixelsFromTop = $('#div_identifier').offset().top;
// Arbitrary calculation to see if target div is 250 pixels away from scroll
if( iPixelsScrolledFromTop > (iDivAreaPixelsFromTop - 250) )
:> //Insert swap logic from above
});

关于javascript - 滚动时使用 jquery 传送一个 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39935966/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com