开发者

How to keep label active when input field inside the label is active?

I have the label like <label>name:<input></label> and the css like label:active{/*properties*/} I'd like the properties to be applied to name inside <label> when I click on <input>开发者_如何学JAVA; it gets applied but it looses focus to the <input> soon after I click it.

here is an example: http://jsfiddle.net/GuCk4/2/


If I understand your question, you could just do this... without changing any HTML.

label, input, input:focus{
    font-weight: bold;
}

Example: http://jsfiddle.net/jasongennaro/GuCk4/4/

BTW: you don't really need input:focus here... at least in my tests on Chrome. You may need it for other browsers.

EDIT

Okay, after @Mohsen's comment, I reread the question.

What you want is a parent selector in css. This does not exist. Since css relies on the cascade, it applies styles down the DOM not up it.

So, the only way to do what you want is to rewrite your HTML, as per @Mohsen's answer, or use some jQuery, like so

$('input').focus(function(){
    $(this).parent().css('font-weight','bold');
});

$('input').blur(function(){
    $(this).parent().css('font-weight','normal');
});

Example 2: http://jsfiddle.net/jasongennaro/GuCk4/5/


label{display:block} label:active,label:hover,label:focus{font-weight:700}

works how you want it to.

@steveax is correct, don't put the label after the input unless it's a checkbox


For anyone using jQuery 1.7+, here's a nicer bit of jQuery to toggle an "active" class on a label wrapped around an <input type="checkbox">.

$("body").on(
  "click",
  "label input[type=checkbox]",
  function(){
    $(this).parent("label").toggleClass("active");
  }
);

Demo: http://jsbin.com/iHaJeCe/3

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜