css “:focus” pseudo-class and selectors

半腔热情 提交于 2020-01-03 04:22:08

问题


I've been battling to get this right...basically I have the following HTML setup:

<div class="box10">
   <span class="label01">Name:</span>
   <input class="tboxes" type="textbox" />
</div>

"span.label01" is an inline element, and appears to the left of the textbox "input.tboxes". What I am trying to do attach some style to "span.label01" AND "div.box10" when the textbox receives focus.

I have tried the following CSS code:

input.tboxes:focus span.label01 {
   color:#FF9900;
   ...
}

but nothing happens. I know this is a CSS selector issue, but I just can't seem to get it right. I have even tried adjacent sibling selectors, and nothing. Can anyone help me here? TIA!


回答1:


Your selector at the moment is looking for a span inside an input. As far as I'm aware, what you're trying to do isn't really reliably possible with the current state of CSS selector support.

I'd be tempted to do it with a bit of jQuery like so:

$("input.tboxes").focus(function() {
    $(this)
    .parent("div:first")
        .addClass("focussed")
        .find("span")
            .addClass("focussed");
});

That should do what you're wanting to do if you then set styling for .label01.focussed and .box10.focussed.




回答2:


This is entirely possible through the use of sibling selectors.

input.tboxes:focus + span.label01 {
   color:#FF9900;
   ...
}

This rule will apply to label01 whenever the input is focused.

However, this only works when the span is to the right of the input, so you'll have to switch the places of the elements. A quick "position:relative" on the div and "float: left" on the span will move them back in place though.




回答3:


No – you can't do this with a CSS selector. Quote from Wikipedia:

Selectors are unable to ascend

CSS offers no way to select a parent or ancestor of element that satisfies certain criteria. A more advanced selector scheme (such as XPath) would enable more sophisticated stylesheets. However, the major reasons for the CSS Working Group rejecting proposals for > parent selectors are related to browser performance and incremental rendering issues.

You could, however, do this with some simple JavaScript:

// with jQuery:
$('input.tboxes').focus(function() {
    $(this).parent().find('span.label01').addClass('active');
});


来源:https://stackoverflow.com/questions/797309/css-focus-pseudo-class-and-selectors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!