我正在嘗試縮小margin-top滾動時的值,因為我使用的是滾動時消失的公告欄。
這是我目前使用的 CSS 腳本,它都在 theme.liquid 檔案中(我使用的是 Shopify):
<script
src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj 3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
crossorigin="anonymous"></script>
<script>
$(window).scroll(function(){
if ($(this).scrollTop() > 50) {
$('#christmas-header-image-pc').addClass('christmas-header-image-margin');
} else {
$('#christmas-header-image-pc').removeClass('christmas-header-image-margin');
}
});
</script>
<style>
#christmas-header-image-pc {
top:0!important;
margin-top:120px;
z-index:5;
height:auto;
position:fixed;
}
.christmas-header-image-margin {
margin-top:55px;
}
</style>
<img id="christmas-header-image-pc" src="https://cdn.shopify.com/s/files/1/0568/1191/3367/files/christmas-header-decoration.svg?v=1638965731">
我似乎無法讓它作業。該值需要從120px到55px。
在前端,這正在發生:

當我滾動時發生這種情況:

任何幫助表示贊賞!提前致謝。
uj5u.com熱心網友回復:
看起來您jQuery的作業正常,新類scrollTop在 50 以上后被添加到影像中。
您的問題與 CSS 特異性有關,將 ID 添加到新的類規則集,如下所示:
#christmas-header-image-pc.christmas-header-image-margin {
margin-top:55px;
}
這是MDN關于特異性主題的一篇很棒的文章。
特異性是瀏覽器決定哪些 CSS 屬性值與元素最相關并因此將被應用的方式。特異性基于由不同種類的 CSS 選擇器組成的匹配規則。
jQuery(window).scroll(function(){
if (jQuery(this).scrollTop() > 50) {
jQuery('#christmas-header-image-pc').addClass('christmas-header-image-margin');
} else {
jQuery('#christmas-header-image-pc').removeClass('christmas-header-image-margin');
}
});
section {
min-height:2000px;
}
#christmas-header-image-pc {
top:0!important;
margin-top:120px;
z-index:5;
height:auto;
position:fixed;
transition:300ms;
}
#christmas-header-image-pc.christmas-header-image-margin {
margin-top:55px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section>
<img id="christmas-header-image-pc" src="https://cdn.shopify.com/s/files/1/0568/1191/3367/files/christmas-header-decoration.svg?v=1638965731">
</section>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/377619.html
