当孩子在CSS中获得焦点时,如何更改父样式

时间:2016-10-27 11:00:50

标签: javascript jquery html css stylesheet

我希望在子<div>元素获得焦点时更改父<input>样式。不幸的是,以下代码根本不起作用。请帮我怎么做?

#email {
    opacity: 0.3;
}

#exampleInputEmail1:focus < #email {
    background: #f90442;
}

<div class="form-group form-group-lg" id="email" tabindex="0">
    <label>Email address</label>
    <input type="email" class="form-control" id="exampleInputEmail1" placeholder="Email">
</div>

4 个答案:

答案 0 :(得分:1)

不幸的是,there are no parent selectors in CSS, not even in CSS3

你必须use a workaround - 即某种javascript。

在每种情况下都必须决定如何使用javascript来解决这个问题。可以说,最容易和最“可访问”的解决方案可能是使用jQuery,并且有很多选择。

例如,您可以使用:has()选择器定位父包装器:

$(".form-group").has(":focus")

这将针对class="form-group [...]"的任何元素,该元素在其后代中具有焦点元素(不仅仅是作为直接子元素)。

或者您可以使用.closest()功能:

$(":focus").closest(".form-group") 

与类似的.parents()函数不同,.closest()在匹配选择器后停止遍历DOM树。这可能会使.closest()更有效地选择两者。

上面两个例子对于DOM结构都是宽松的,如果它发生变化则不太可能中断。但是,如果包装元素始终<input>的直接父级,则可以使用.parent()函数(使用可选的选择器):

// Option 1: Targets the immediate parent
$("input:focus").parent()
// Option 2: Targets the immediate parent, but only if it's a div
$("input:focus").parent("div")

这四个选项的示例实现,通过在包装器上切换.infocus类(也可用作jsfiddle)来实现:

// Adds or removes a focus class.
function updateFocus(e) {
	// Log the event to view details about it
  // console.log(e);
  
  // The "has focus" class name
  var focusClass = "infocus";
  // The wrapper element selector
  var wrapperSel = ".form-group";
  
  
  //*===========================================================
  // Option 1: has(":focus")
  // - needs only the wrapper selector
  // ===========================================================
  var wrapper = $(wrapperSel);
  // Remove the class on all
  //wrapper.each(function() { $(this).removeClass(focusClass);});
  wrapper.removeClass(focusClass);
  // Add class only to the one whose descendant has focus
  wrapper.has(":focus").addClass(focusClass);
  //*/
  
  /* ===========================================================
  // Option 2: closest()
  // - needs the event and the wrapper selector
  // ===========================================================
  if (e.type === "focus") {
  	$(e.target).closest(wrapperSel).addClass(focusClass);
  } else if (e.type === "blur") {
    $(e.target).closest(wrapperSel).removeClass(focusClass);
  }
  //*/
  
  /* ===========================================================
  // Option 3: parents()
  // - needs the event and the wrapper selector
  // ===========================================================
  if (e.type === "focus") {
  	$(e.target).parents(wrapperSel).addClass(focusClass);
  } else if (e.type === "blur") {
    $(e.target).parents(wrapperSel).removeClass(focusClass);
  }
  //*/
  
  /* ===========================================================
  // Option 4: parent()
  // - needs only the event (the wrapper selector is optional)
  // ===========================================================
  if (e.type === "focus") {
  	$(e.target).parent().addClass(focusClass);
  } else if (e.type === "blur") {
    $(e.target).parent().removeClass(focusClass);
  }
  //*/
}

// Bind the updateFocus() function above to focus/blur of form elements.
$('input, textarea, select').on("focus", function(event) {
	updateFocus(event);
}).on("blur", function(event) {
	updateFocus(event);
});
.form-group {
    opacity: 0.3;
}
.form-group.infocus {
  opacity: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
  <label>Email</label>
  <input type="email" placeholder="Email">
</div>

<div class="form-group">
  <label>Name</label>
  <input type="text" placeholder="Name">
</div>

答案 1 :(得分:0)

使用jQuery。

  private class CustomerEventsAdapter extends BaseAdapter {
            private Context myContext;
            private ArrayList<Events> myEventArrayList;

            private LayoutInflater mInflater;
            private Boolean isSelected = false;

            public EventsAdapter(Context ctx, ArrayList<Events> theArrayListEvents) {
                this.myContext = ctx;
                this.myEventArrayList = theArrayListEvents;
                mInflater = LayoutInflater.from(ctx);

            }

            @Override
            public int getCount() {
                return myEventArrayList.size();
            }

            @Override
            public Object getItem(int i) {
                return myEventArrayList.get(i);
            }

            @Override
            public long getItemId(int i) {
                return i;
            }

            @Override
            public View getView(final int i, View convertView, ViewGroup viewGroup) {
                View view = convertView;
                if (view == null) {
                    view = mInflater.inflate(R.layout.event_item_list, null);
                    final ViewHolder holder = new ViewHolder();


                    holder.myCheckBoxCustomerEventItem = (CheckBox) view.findViewById(R.id.checkBoxCustomerEventItem);





                    holder.myCheckBoxCustomerEventItem.setOnClickListener(new View.OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            Events events = myEventArrayList.get(i);
                            //is chkIos checked?
                            if (((CheckBox) v).isChecked()) {
                                holder.myCheckBoxCustomerEventItem.setChecked(true);
                                eventsInfo.setMyIsSelected(true);
                            } else {
                                holder.myCheckBoxCustomerEventItem.setChecked(false);
                                eventsInfo.setMyIsSelected(false);
                            }
                            //case 2

                        }
                    });




                    view.setTag(holder);

                }

                if (view != null) {
                    ViewHolder holder = (ViewHolder) view.getTag();
                    Events eventsInfo = myEventArrayList.get(i);

                    boolean isChecked = eventsInfo.getMyIsSelected();


                    if (isChecked) {
                        holder.myCheckBoxCustomerEventItem.setChecked(true);


                    } else {
                        holder.myCheckBoxCustomerEventItem.setChecked(false);


                    }
                }

                return view;
            }
        }

答案 2 :(得分:0)

  

截至目前,CSS中无法满足您的要求。所以只有   选项是使用Jquery。

如果有兴趣请继续阅读..

使用jquery绑定on focus元素上的input事件。在这种情况下,您只需访问parent并更改其background-color

拥有如下的CSS。

.background-color-RED{
  background-color:#f90442;
}

Jquery语法如下。

$("#exampleInputEmail1").on('focus',function() {
   $(this).parent().addClass('background-color-RED');
});

额外:如果您想在用户从输入中移开时删除背景色,则可以使用blur事件并按以下方式处理。

 $("#exampleInputEmail1").on('blur',function() {
    $(this).parent().removeClass('background-color-RED');
 });

答案 3 :(得分:0)

快速更新这个,这可以使用 focus-within 来完成:

/* Selects a <div> when one of its descendants is focused */
div:focus-within {
  background: cyan;
}