如何在页面加载时运行脚本?

时间:2014-11-13 16:14:51

标签: jquery mouseover onhover

这个脚本从上到下绘制一条线,但它从鼠标悬停开始#34; onhover"我希望它在打开页面时绘制它。

这是整个代码要清楚。它实现功能的唯一方法是从这一行$( this ).hover(function()悬停。

var animationDuration = "0.4"
var backgroundColor = "white"

$.fn.line = function liner(animationDuration, borderWidth, side, backgroundColor) {
    var className = "line"
    var timePerSide = animationDuration

    $(this).append('<div class=' + className + '> <div></div> </div>');

    $(this).children("." + className).css({
        "-webkit-transition": "all " + timePerSide + "s linear " + timePerSide * 0 + "s",
        "transition": "all " + timePerSide + "s linear " + timePerSide * 0 + "s",
        "background-color": backgroundColor,
    });

    switch (true) {
        case side == "right":
            $(this).children(".line").css({
                "top": "0",
                "right": "-10",
                "height": "0%",
                "width": borderWidth,
            });
    }

    if (side == "right") {
        $(this).hover(function () {
            $(this).children(".line").css({
                "height": "150%",
            });
        });
    }
};

这是我的HTML

<body>
<div class="box1 float-left liner">
<h1>Lorem</h1>
</div>
</body>
<script type="text/javascript">
    $( document ).ready(function() {
        $('.liner').line(animationDuration, "5px", "right", backgroundColor);
    });
    </script>
</html>

1 个答案:

答案 0 :(得分:0)

听起来你想要忽略悬停功能,只需在加载时运行一部分插件。您必须修改插件,这可能不是主意。而不是:

if (side == "right") {
    $(this).hover(function () {
        $(this).children(".line").css({
            "height": "150%",
        });
    });
}

...只需这样做:

if (side == "right") {
    $(this).children(".line").css({
        "height": "150%",
    });
}

如果您需要在两个事件上运行代码,您可以将内部部分拉出到命名函数中并为它们调用它:

function setLineHeight(els) {
    $(els).children(".line").css({
        "height": "150%",
    });     
}

......然后:

if (side == "right") {
    $(this).hover(function () {
        setLineHeight(this);
    });

    setLineHeight(this); // called when the plugin is initialized (on document.ready)
}