【问题标题】:Can i trigger browser to focus element in JS我可以触发浏览器聚焦JS中的元素吗
【发布时间】:2022-02-10 16:46:51
【问题描述】:

当我想专注于某个元素时,我使用 focus() 函数,它从 css 中给了我 :focus。问题是,当我专注于 TAB 键盘按钮时,我会从 css 获得样式,但也会在元素周围获得一些蓝色样式,这可能是浏览器的焦点。我也可以用 js 以某种方式触发蓝色浏览器焦点吗?

【问题讨论】:

    标签: javascript html css google-chrome focus


    【解决方案1】:

    您可以使用focus-visible CSS 覆盖它。在下面添加示例工作示例以供参考

    button {
      background: #F0FF00;
      border: 1px solid #ccc;
      font-size: 18px;
    }
    
    .clear-focus {
      background: #00FF00;
    }
    
    .clear-focus:focus-visible, .clear-focus:focus  {
      outline: none;
      box-shadow: 0px 1px 6px 0px #000;
    }
    <input placeholder="click to focus here manually" type="text" />
    
    <p>Now press tab</p>
    <button >Button without focus override / default focuss css</button>
    
    
    <p>Now press tab agian</p>
    <button class="clear-focus">Override focuss css /  with custom css</button>

    isible` CSS 类。示例代码如下:

    【讨论】:

      【解决方案2】:

      我们可以使用outline: none;,它隐藏了轮廓

      :not(.focusable){
        outline: none;
      }
      <input placeholder="You can't focus me*" type="text" />
      
      <p>press tab</p>
      
      <button class="focusable">You can focus me</button>
      <button >You can't focus me*</button>
      
      <p>again repeat</p>
      
      <input placeholder="You can't focus me*" type="text" />
      
      <p>press tab</p>
      
      <button class="focusable">You can focus me</button>
      <button >You can't focus me*</button>
      
      
      <p>*Focus is possible to all element,but border is only hided,as per OP's question</p>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-11-13
        • 2019-02-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-17
        • 2021-08-26
        • 2011-08-03
        相关资源
        最近更新 更多