【问题标题】:How can I hide an element?如何隐藏元素?
【发布时间】:2016-11-08 12:34:20
【问题描述】:

我正在尝试禁用浏览器的“保存密码”功能(我的 previous question)。为此,我只是在表单中添加了一个新的输入 type="password" 字段,所以这是代码:

<form method="post" action="yoururl">
    <input type="password" style="display:none"/><!-- Making "Save Password" disable -->
    <input type="text" name="username" placeholder="username"/>
    <input type="password" name="password" placeholder="password"/>
</form>

注意:使用autocomplete=false 不适用于现代浏览器。所以请不要建议。事实上我正在尝试使用this approach

那是什么问题?当我隐藏display:none 的无用输入时,它不起作用(我的意思是保存密码选项仍然存在。) .但是当我隐藏visibility:hidden 的无用输入时,它就起作用了。

如您所知,可见性属性占用了我不希望的页面空间。那么如何隐藏那些无用的输入以既隐藏它又删除它的空间呢?

  • display:none 很好,但破坏了我添加无用输入的目的。
  • visibility:hidden 不好,因为它占用了页面空间。

那么还有其他方法吗?

【问题讨论】:

  • position: absolute; left: -9999px
  • @RoryMcCrossan 是的,它有效,但看起来真的很不正常(丑陋) :-)
  • 这并不理想,但在元素必须占用 DOM 中的空间但您不希望它被看到的情况下,您可以这样做。它也适用于预加载图像。
  • 如果您希望禁用&lt;input&gt; 以进行鼠标交互,可以添加pointer-events: none

标签: jquery html css


【解决方案1】:

有很多可能的解决方案。

一个可能是:

input[type='password']:nth-of-type(1) {
visibility: hidden;
width: 1px;
height: 1px;
}

【讨论】:

  • 为什么不0px ? :)
  • 我不确定浏览器是否会接受这一点,但 width:0; height:0; 毕竟似乎没问题。
  • @Rounin 其实是有区别的。如果你声明width和height为0px,浏览器会认为该元素是display: none,屏幕阅读器将无法使用该元素。
【解决方案2】:

看到这个answer

我认为方法 1 最适合您,即将元素的 widthheight 设置为 0。

【讨论】:

    【解决方案3】:

    您可以通过 autocomplete="new-password" 禁用自动填充

    但如果你想删除空间,只需将 position 设置为 absolute 并使用 z-index: -9999; 将其隐藏在正文后面

    .fakepassword {
        visibility: none;
        position: absolute;
        z-index: -9999;
    }
    

    【讨论】:

    • autocomplete="new-password" 完美运行.. 谢谢.. 点赞
    猜你喜欢
    • 1970-01-01
    • 2016-06-19
    • 1970-01-01
    • 2011-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-01
    • 1970-01-01
    相关资源
    最近更新 更多