单击复选框后,如何阻止浏览器在页面顶部滚动?

时间:2013-07-31 15:07:00

标签: html css

每当我点击复选框时,浏览器窗口(firefox)将在屏幕顶部滚动 如何防止此行为,因此当我单击复选框时,浏览器窗口不会在顶部滚动?
这是从http://jsfiddle.net/zAFND/6/发现的代码 谢谢。

<html>
    <head>
        <title>Test</title>
        <style>
            div label input {
                margin-right: 100px;
            }

            body {
                font-family:sans-serif;
            }

            #ck-button {
                margin: 4px;
                background-color: #EFEFEF;
                border-radius: 4px;
                border: 1px solid #D0D0D0;
                overflow: auto;
                float: left;
            }

            #ck-button {
                margin: 4px;
                background-color: #EFEFEF;
                border-radius: 4px;
                border: 1px solid #D0D0D0;
                overflow: auto;
                float: left;
            }

            #ck-button:hover {
                margin: 4px;
                background-color: #EFEFEF;
                border-radius: 4px;
                border: 1px solid red;
                overflow: auto;
                float: left;
                color: red;
            }

            #ck-button label {
                float: left;
                width: 4.0em;
            }

            #ck-button label span {
                text-align: center;
                padding: 3px 0px;
                display: block;
            }

            #ck-button label input {
                position: absolute;
                top: -20px;
            }

            #ck-button input:checked + span {
                background-color: #911;
                color: #fff;
            }
        </style>    
</head>
    <body>
        <br>
        <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
        <div id="ck-button">
            <label>
                <input type="checkbox" value="1"><span>red</span>
            </label>
        </div>
    </body>

3 个答案:

答案 0 :(得分:27)

问题在于这个规则:

#ck-button label input {
    position:absolute;
    top:-20px;
}

当您单击标签时,浏览器会尝试聚焦相关输入。在您的情况下,checkbox元素位于页面顶部,即使在视口的外部也是如此。所以Firefox试图在那里滚动。

我认为你可以通过添加:

来解决这个问题
#ck-button label {
    display: block;
    position: relative;
    overflow: hidden;
}

<强>演示

Try before buy

修改

今天我回到这个答案,关于Heisenberg's:他指出了一个问题,可以通过使用极值来解决,并添加另一个基本上和我一样的怪癖的解决方案。

为了避免这些可能的怪癖,这是另一种可能的解决方案,只需隐藏输入即可。功能不受影响,您可以在下面的链接中进行测试。

<强> CSS

#ck-button label input {
    display: none;
}

<强>演示

Second demo

答案 1 :(得分:14)

接受的答案并非完全正确。有效,但并非在所有情况下都有效。

如果使用公共css隐藏“top”属性中的元素(可能是-999em或类似),在这种情况下 position:relative无关,因为-999em总是比视口高很多

接受的答案很好,因为“顶部”只有-20px。尝试将其设置为更高的数字,您将看到问题。

所以,解决方案不是设置相对位置。 我认为正确的方法只是在左侧位置设置负值(不是顶部)。

试试吧。 :)

答案 2 :(得分:3)

您可以隐藏您的复选框输入,如下所示:

#ck-button label input {
    position:absolute;
    top:+20px;
    visibility: hidden;
}