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

前端之家收集整理的这篇文章主要介绍了html – 如何在单击复选框时阻止浏览器在页面顶部滚动?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
每当我点击复选框时,浏览器窗口(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>

解决方法

问题是这个规则:
#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

原文链接:https://www.f2er.com/html/231846.html

猜你在找的HTML相关文章