微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.jb51.cc/html/231846.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐