单击特定的单元格时,我尝试隐藏表的特定行。但是,当目标行块被隐藏时,屏幕会自动滚动到页面顶部。主单元格是可单击的,并允许隐藏以下关联的单元格。我的桌子很大,它们是多个可点击的单元格。

这是我的代码的简单版本:

<tr id="Main1" onclick="hideTr(this.id)"><td><a href="#">Main1</a></td></tr>
    <tr class = "main1Tr"><td>Cell1</td>
    </tr>
    <tr class = "main1Tr"><td>Cell2</td>
    </tr>
<tr id="Main2" onclick="hideTr(this.id)"><td><a href="#">Main2</a></td></tr>
        <tr class = "main2Tr"><td>Cell3</td>
        </tr>
        <tr class = "main2Tr"><td>Cell4</td>
        </tr>

function hideTr(id){
if(id=="Main1"){
    loading = document.getElementsByClassName("main1Tr");
        for (var i = 0; i < loading.length; i++){
            display = loading[i].style.display;
            if(display ==  "none"){loading[i].style.display="";}
            if(display ==  ""){loading[i].style.display="none";}
        }
    }
if(id=="Main2"){
        loading = document.getElementsByClassName("main2Tr");
            for (var i = 0; i < loading.length; i++){
                display = loading[i].style.display;
                if(display ==  "none"){loading[i].style.display="";}
                if(display ==  ""){loading[i].style.display="none";}
            }
        }
}

最佳答案

您必须返回false onclick
尝试onclick =“ hideTr(this.id);返回false”

关于javascript - 当显示元素设置为无时,如何避免屏幕自动滚动,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33777675/

10-11 13:16