javascript - 如何重新启动Javascript或结合onclick mouseenter mouseleave?

标签 javascript jquery

这是我的 JS,仅在第一次时有效(需要刷新才能再次工作)

  $('.example-form').on('click', function(e){
      e.preventDefault();
      $(this).toggleClass('myClickState');
      });

   $('.example-form').on('mouseenter', function(e){
      e.preventDefault();
      $(this).toggleClass('myClickState');
      });

   $('.example-form').on('mouseleave', function(e){
      e.preventDefault();
      $( this ).css("border-color","rgba(0, 0, 0, .075)");
      });

这是适用于悬停操作的代码,但我似乎无法正确添加点击功能:

$(document).ready(function(){

  $( ".example-form" )
  .mouseenter(function() {
  $( this ).css("border","red solid 1px");
  })
      .mouseleave(function() {
  $( this ).css("border-color","rgba(0, 0, 0, .075)");
  });
});

如何添加 onclick 函数以便它与后面的代码一起使用?

我希望在单击时搜索表单框,边框变为红色,在搜索框外单击时,边框会消失。悬停时,边框变为可读。

最佳答案

我认为你需要这样的东西:

$(document).ready(function(){
    $(window)
       .click(function() {
        $( ".example-form" ).css("border","rgba(0, 0, 0, .075) solid 1px");
    });

    $('.example-form')
        .click(function(event){
            event.stopPropagation();
            $( this ).css("border","red solid 1px");
        })
        .mouseenter(function() {
            $( this ).css("border","red solid 1px");
        });
});

但您必须知道,应该避免使用 stopEventPropagation(),因为它会破坏 DOM 中的正常事件流。

另一种变体是使用 .focusout()

 $(document).ready(function(){
    $('.example-form')
        .focusout(function(){
            $( this ).css("border","rgba(0, 0, 0, .075) solid 1px");
        })
        .click(function(){
            $( this ).css("border","red solid 1px");
        })
        .mouseenter(function() {
            $( this ).css("border","red solid 1px");
        });
});

您可以在这里阅读 http://api.jquery.com/focusout/

关于javascript - 如何重新启动Javascript或结合onclick mouseenter mouseleave?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52913636/

相关文章:

javascript - 为什么我的 jQuery 事件处理程序在附加到多个元素时会失败?

javascript - jQuery 如何使弹出窗口在计时器上出现/消失?

javascript - 如何使用jquery编辑表td值

javascript - 未捕获的 TypeError : undefined is not a function, 在 for 循环中创建的对象

javascript - Chrome "Drop workspace folder here"

javascript - ^((?<!\/)\/[A-Za-z0-9_-]*)+$ 的正则表达式无效量词

jquery - 使用 json 向 RESTful WCF 发送 Post 请求

javascript - 获取 iframe 的当前位置/url 并分配给变量

javascript - 使用javascript从输入开始循环到结束日期

javascript - 在 Google map 上绘制文字