【问题标题】:Style ancestor element of form input:focus (jQuery)表单输入的样式祖先元素:焦点(jQuery)
【发布时间】:2008-11-19 12:17:32
【问题描述】:

我有一个带有 DIV、3 个输入的表单,每个输入都位于一个 LABEL 元素中。我想在关注每个 INPUT 时更改 DIV 元素的背景图像。

我无法返回 DOM 以使用 CSS 解决此问题,所以有人可以建议几行 jQuery 吗?

谢谢

【问题讨论】:

    标签: jquery css focus background selector


    【解决方案1】:
    $('div input').focus(function(){
        $(this).parents('div:eq(0)').addClass('specialCSSclass');
    }).blur(function(){
        $(this).parents('div:eq(0)').removeClass('specialCSSclass');
    });
    

    您需要在 CSS 中创建一个类,然后用它替换“specialCSSclass”。

    【讨论】:

      【解决方案2】:
      $('input').focus(function(){
          $(this).parent().parent().addClass('highlight');
      }).blur(function(){
           $(this).parent().parent().removeClass('highlight');
      });
      

      【讨论】:

        【解决方案3】:

        jQuery最接近也是一个选项。

        closest( selector )
            .closest( selector )
            .closest( selector, [ context ] )
        closest( selectors, [ context ] )
            .closest( selectors, [ context ] )
        

        根据描述.. 获取与选择器匹配的第一个祖先元素,从当前元素开始,向上遍历 DOM 树。

        http://api.jquery.com/closest/

        【讨论】:

          猜你喜欢
          • 2016-12-27
          • 1970-01-01
          • 1970-01-01
          • 2019-03-13
          • 2019-05-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多