无法实现 JavaScript 代码

Cannot implement a JavaScript Code

本文关键字:代码 JavaScript 实现      更新时间:2023-09-26

我找到了这段代码

$(window).scroll(function(){
    $('#header').css({
        //Why this 15, because in the CSS, we have set left 15, so as we scroll, we would want this to  remain at 15px left
        'left': $(this).scrollLeft() + 15  
    });
});

它完全符合我的需求,但我不知道如何在我的 HTML 或 CSS 中实现它。谁能帮我?我真的很感激。

该代码使用 jQuery,因此您需要在页面中包含 jQuery。

因为它是JavaScript,所以你需要使用<script />标签。您可以内联添加代码(我会这样做,因为它更容易解释),但您应该考虑将其添加到单独的 JS 文件中并包含它。

在任何地方将其添加到您的 HTML 中;

<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script> <!-- Include jQuery -->
<script type="text/javascript">
    $(window).scroll(function(){
        $('#header').css({
            //Why this 15, because in the CSS, we have set left 15, so as we scroll, we would want this to  remain at 15px left
            'left': $(this).scrollLeft() + 15  
        });
    });
</script>

通常,您必须添加一个就绪处理程序,但是如果您要附加到窗口,则不会,因为它始终存在。