1 回答

TA貢獻1777條經驗 獲得超3個贊
該問題強調了幾個問題:當轉換在絕對和固定之間移動時的“跳轉”以及偽元素的內容無法轉換的事實。
為了解決絕對到固定的跳轉問題,我們可以在轉換開始后立即將按鈕設置為固定,然后進行轉換。這可以通過引入 CSS 動畫而不是過渡來實現。
為了在內容之間進行轉換,我們使用 before 偽元素來保存初始文本(如給定的代碼中所示),并引入一個 after 偽元素來保存 svg。為了呈現兩者之間的過渡效果,我們設置了不透明度的動畫。
注意:在要模擬的網站中,按鈕最初在頁面的白色背景上有一個白色背景。這意味著初始按鈕消失時形狀的變化不太明顯。在對比鮮明的藍色背景下,形狀的變化更加明顯。這可能是也可能不是所需的效果。
這是一個帶有動畫而不是過渡的片段,并在動畫開始時立即移動到固定位置。
$(document).ready(function() {
$(window).on('scroll', function() {
if ($(window).width() <= 2500) {
var scrollTop = $(this).scrollTop();
$('.button').each(function() {
var topDistance = $(this).offset().top;
if ((topDistance - 30) < scrollTop) {
$(this).addClass('floating');
} else if ((topDistance - 100) >= scrollTop){
}
});
}
});
});
.section {
height: 2000px;
width: auto;
position: relative;
}
.button, .button::before, .button::after {
animation-duration: 1.5s;
animation-iteration-count: 1;
animation-fill-mode: forwards;
animation-timing-function: ease-in-out;
position: absolute;
}
.button {
transform: translateX(50%);
right: 50%;
line-height: 60px;
height: 60px;
width: auto;
color: transparent; /* do this to ensure the button has dimensions so it can be clicked */
display: inline-block;
vertical-align: middle;
top: 15rem;
}
.button.floating {
position: fixed;
top: 30px;
animation-name: floatdown;
}
.button::before {
content: 'Button\00a0 Text';
opacity: 1;
color: white;
line-height: 60px;
height: 60px;
width: auto;
padding-left: 25px;
padding-right: 25px;
background-color: blue;
border-radius: 25px;
}
.button::after {
content: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='24px' height='24px' fill='white'><path d='M7.41,8.58L12,13.17L16.59,8.58L18,10L12,16L6,10L7.41,8.58Z' /></svg>");
opacity: 0;
padding-left: 0px;
padding-right: 0px;
height: 80px;
width: 80px;
margin-left: -50%;
background-color: red;
border: none;
border-radius: 50%;
justify-content: center;
text-align: center;
}
div.button.floating::before {
animation-name: fadeout;
}
div.button.floating::after {
animation-name: fadein;
}
@keyframes fadeout {
100% {
opacity: 0;
}
}
@keyframes fadein {
100% {
opacity: 1;
}
}
@keyframes floatdown {
100% {
top: calc(100vh - 120px);
right: 95px; /* 80+15px */
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="section">
<div class="button">Button text</div>
</div>
另請注意,如果您希望向下箭頭更多地填充圓圈,您可以將其作為尺寸包含的背景圖像而不是內容。
添加回答
舉報