【问题标题】:Javascript set button activeJavascript设置按钮激活
【发布时间】:2021-02-03 01:44:35
【问题描述】:

我有一个按钮表,一旦填充,我正在使用

document.getElementById("btn0").click();

点击第一个按钮。按钮正在做它应该做的事情,但是按钮的背景颜色并没有像我手动单击它时那样改变。

正如您在运行时看到的那样,div 的背景颜色正在改变,但按钮未设置为活动状态。

代码片段:

var myfunc = function(){
    document.getElementById("test").style.backgroundColor="red";
};

document.getElementById("btn0").click();
.btn{
  border: none;
  color: white;
  width: 100%;
  padding: 5px 5px 5px 5px;
  height: 50px;
  cursor: pointer;
  font-size: 12px;
  background-color: #343a40;
}

.btn:active .btn.active{
  background-color:green;
  outline: none;
}

.btn:focus{
  background-color:green;
  outline: none;
}

#test{
  background-color: green;
  width: 600px;
  height: 400px;
}
<button class="btn" onclick="myfunc()" id="btn0"> Cool button</button>

<div id="test">
  Hello
</div>

这是我创建的 jsfiddle 的链接: https://jsfiddle.net/58hrwcgo/3/

【问题讨论】:

    标签: javascript html css


    【解决方案1】:

    There's a difference between click and focus.

    click() 点击元素然后取消焦点,不像真正的鼠标点击,点击然后聚焦。

    我建议通过两种方式模拟真实点击:

    document.getElementById("btn0").click();
    document.getElementById("btn0").focus();
    

    【讨论】:

      【解决方案2】:

      js

      const btn = document.getElementById("btn0")
      var myfunc = function(){
          document.getElementById("test").style.backgroundColor="red";
          btn.focus();
      };
      
      btn.click();
      

      css

      ...
      
      .btn:active, .btn.active{
        background-color:green;
        outline: none;
      }
      
      ...
      

      【讨论】:

        【解决方案3】:

        手动单击时,首先触发焦点状态。这就是为什么外观会根据你的班级而变化.btn:focus。

        document.getElementById("btn0").focus();
        document.getElementById("btn0").click();
        

        将导致所需的行为。

        此外,您在 :active 状态内的 CSS 示例中缺少冒号:

        .btn:active, .btn.active { ... }
        

        【讨论】:

          【解决方案4】:

          你可以试试 HTML DOM focus() 方法。

           document.getElementById("btn0").focus(); 
          

          您可以在here 中阅读更多相关信息。

          【讨论】:

          • 猜猜我的答案被删除了,无论如何,非常感谢你的帮助:)
          猜你喜欢
          • 1970-01-01
          • 2013-07-14
          • 2019-05-25
          • 1970-01-01
          • 2016-03-15
          • 2011-05-01
          • 2018-08-04
          • 1970-01-01
          • 2021-07-30
          相关资源
          最近更新 更多