gpt4 book ai didi

javascript - 如何使用 jQuery 基于 offset().top 操作 translateY()

转载 作者:行者123 更新时间:2023-11-30 14:30:32 26 4
gpt4 key购买 nike

我正在玩一个小的 jQuery 片段,它通过根据元素距窗口的偏移量操纵“顶部”值来更改固定元素的位置。

我创建了这个 jsFiddle 来更好地说明我的意思: jsFiddle

这是简单的 jQuery 代码:

function switchIt () {
$('.text-two').each(function() {
$(this).css('top',
$('.text-one').offset().top - $(this).closest('.content').offset().top
);
});
};

$(document).scroll(function() {switchIt();});

switchIt();

效果很好,但实际上我想使用 css 函数 translateY() 而不是 top 来更改位置。

例如:top: 100px; 应该是transform: translateY(100px);

我知道这应该很容易,但我很不好意思展示我试图让它发挥作用的步骤。我遗漏了一些非常简单的东西,但不知何故找不到位置。

提前感谢您的宝贵时间。

最佳答案

您需要使用 transfrom 更改顶部并删除 100px,这是在 CSS 中添加的默认顶部值:

function switchIt () {
$('.text-two').each(function() {
$(this).css('transform','translateY('+(
$('.text-one').offset().top - $(this).closest('.content').offset().top-100)+'px)'
);
});
};

$(document).scroll(function() {switchIt();});

switchIt();
* {
padding: 0;
margin: 0;
}

.content {
min-height: 100vh;
overflow: hidden;
position: relative;

}

.content div {
top: 100px;
left: 100px;
}

.text-one {
position: fixed;
color: blue
}

.text-two {
position: absolute;
color: white
}

.blue {
background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="content">
<div class="text-one">Scroll down to see</div>
</section>

<section class="content blue">
<div class="text-two">Scroll down to see this Text changing</div>
</section>

或者简单地从 CSS 中删除顶部:

function switchIt () {
$('.text-two').each(function() {
$(this).css('transform','translateY('+(
$('.text-one').offset().top - $(this).closest('.content').offset().top)+'px)'
);
});
};

$(document).scroll(function() {switchIt();});

switchIt();
* {
padding: 0;
margin: 0;
}

.content {
min-height: 100vh;
overflow: hidden;
position: relative;

}

.content div {
left: 100px;
}

.text-one {
position: fixed;
top:100px;
color: blue
}

.text-two {
position: absolute;
color: white
}

.blue {
background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="content">
<div class="text-one">Scroll down to see</div>
</section>

<section class="content blue">
<div class="text-two">Scroll down to see this Text changing</div>
</section>

关于javascript - 如何使用 jQuery 基于 offset().top 操作 translateY(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51268089/

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