单击样式切换器跳转到页面顶部

时间:2014-09-10 03:16:20

标签: javascript jquery css ajax styleswitching

我有样式切换器,使用php和jquery来实现它。现在,当我点击其按钮打开时,页面会跳转到页面顶部。当我点击相同的按钮关闭样式框时。同样的事情它会跳到页面顶部。如何更改代码,使其无需跳转即可打开。

jQuery.fn.styleSwitcher = function(){
    $(this).click(function(){
        // We're passing this element object through to the
        // loadStyleSheet function.
        loadStyleSheet(this);
        // And then we're returning false.
        return false;
    });

    function loadStyleSheet(obj) {
        $.get( obj.href+'&js',function(data){

            // Select link element in HEAD of document (#stylesheet) and change href attribute:
            $('#stylesheet').attr('href','css/' + data + '.css');

            // Check if new CSS StyleSheet has loaded:

        });
    }
}

$(document).ready(function () {
    $(".toggleDiv .expand-arrow").show();
    $(".toggleDiv .shrink-arrow").hide();

    $(".toggleDiv .expand-arrow").click(function(){
        $("#style-switcher").animate(
        {"left": "0"}, "slow");

        $("#swatchesDiv").animate(
        {"opacity": "1"}, "slow");

            $(".toggleDiv .expand-arrow").hide();
        $(".toggleDiv .shrink-arrow").show();
    }); 

    $(".toggleDiv .shrink-arrow").click(function(){
        $("#style-switcher").animate(
        {"left": "-200px"}, "slow");

        $("#swatchesDiv").animate(
        {"opacity": "0"}, "slow");

        $(".toggleDiv .expand-arrow").show();
        $(".toggleDiv .shrink-arrow").hide();
    });  
});

1 个答案:

答案 0 :(得分:0)

您应该使用preventDefaultreturn false

禁用链接的行为
$(document).ready(function () {
    $(".toggleDiv .expand-arrow").show();
    $(".toggleDiv .shrink-arrow").hide();

    $(".toggleDiv .expand-arrow").click(function(e){
        e.preventDefault(); // disable the link
        $("#style-switcher").animate(
        {"left": "0"}, "slow");

        $("#swatchesDiv").animate(
        {"opacity": "1"}, "slow");

            $(".toggleDiv .expand-arrow").hide();
        $(".toggleDiv .shrink-arrow").show();
    }); 

    $(".toggleDiv .shrink-arrow").click(function(e){
        e.preventDefault(); // disable the link
        $("#style-switcher").animate(
        {"left": "-200px"}, "slow");

        $("#swatchesDiv").animate(
        {"opacity": "0"}, "slow");

        $(".toggleDiv .expand-arrow").show();
        $(".toggleDiv .shrink-arrow").hide();
    });  
});
相关问题