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

style switcher when clicked jumps to the top of the page

本文关键字:顶部 切换器 单击 样式      更新时间:2023-09-26

我有style switcher,使用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();
    });  
});

您应该使用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();
    });  
});