【问题标题】:React ref's focus behaviour is not consistent in chrome,firefox and IEReact ref 的焦点行为在 chrome、firefox 和 IE 中不一致
【发布时间】:2020-07-02 18:20:12
【问题描述】:

我在 react 中使用 refs。我注意到 .focus() 方法在 chrome 和 firefox 中并不一致。

在这个沙箱https://codesandbox.io/s/a-guide-to-react-refs-2nd-example-vl9sj?file=/src/Ref.js

我创建了很多输入字段,第一个输入字段中有 ref。当用户单击提交按钮时,我在输入参考上调用 .focus() 方法。

如下图所示。

左图->火狐

右像素-> Chrome

正如您所见,chrome 在聚焦时会在其上方添加一定的空间,而 Firefox 则不会。这与 IE 中显示的行为相同。

有什么方法可以让他们两者的行为保持一致。或者除了焦点之外我还能做些什么来获得焦点行为?

在 IE 中编辑:

.focus {
  outline: #015ecc solid 2px;
  outline-offset: -2px;  // You don't always need to provide offset. But in some scenarios you might need to provide outline offset as it's not default offset property.
      ::-ms-focus-inner {  //FF adds some inner border to the elements, this will remove it.
        border: 0;
      }
    }

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    是的,当您聚焦时,您会在不同的浏览器中获得不同的行为。

    Chrome 使用 webkit-focus-ring 在元素部分中,当您聚焦元素时,您可以看到类似这样的内容,

    outline: webkit-focus-ring-color auto 2px;
    

    在FF中,这个大纲会有所不同。

    因此,为了在多个浏览器中获得一致的焦点行为,您需要提及您的大纲行为。

    在你的 css 中你必须做如下的事情,

        .focus {
        outline: #015ecc solid 2px;
        outline-offset: -2px;  // You don't always need to provide offset. But in some scenarios you might need to provide outline offset as it's not default offset property.
            ::-moz-focus-inner {  //FF adds some inner border to the elements, this will remove it.
              border: 0;
            }
          }
    

    因此,通过添加上述 CSS,您将在所有浏览器中获得一致的行为焦点。根据您的用例,您可能需要使用伪选择器添加此 CSS,例如 ::after、::before。

    从您的沙盒链接添加屏幕截图以更清晰,

    希望对你有帮助!!!

    【讨论】:

    • 谢谢它的帮助。我相信这也可以在 IE 中使用,对吧?
    • 对于 IE,目前还不确定。但我想它也会起作用,因为我们指定我们需要大纲。如果没有,请告诉我很乐意提供帮助:)
    • 我认为它没有占用财产
    • 是的,它在 IE 中不起作用。如果您确实需要支持 IE,请看一下这个问题,stackoverflow.com/questions/13112968/… 这应该与我的更改合并以满足您的要求。
    猜你喜欢
    • 2016-08-20
    • 2015-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-20
    • 1970-01-01
    相关资源
    最近更新 更多