在输入焦点上改变标签的颜色。怎么样?

时间:2014-01-16 06:19:32

标签: less

在输入focus上我想更改标签元素的颜色。我怎样才能更少地实现这一目标?

.control-label{
      color: @gray-light;
}
.controls{
  input,
  textarea{
    background-color:red; 
    &:focus{
      .control-label &{
        color: red;  //HERE
      }

    }
}

HTML:

<div class="control-group">
    <label class="control-label" for="inputEmail">Firstname</label>
    <div class="controls">
        <input type="text" id="inputEmail" placeholder="Firstname">
    </div>
</div>

6 个答案:

答案 0 :(得分:13)

我认为你不能不改变你的HTML,另见:Is there any way to hover over one element and affect a different element?,你的元素应该是直接的兄弟姐妹。 (LESS在这里没有帮助解决你的问题,LESS生成CSS而且似乎无法在CSS中完成)

可能的建议:

input:focus + .control-label
{
    background-color:purple;
    color: red;
}
.controls > input
{
    float:right;
}	
<div class="controls">
    <input type="text" id="inputEmail" placeholder="Firstname">
    <label class="control-label" for="inputEmail">Firstname</label>
</div>

或者使用javascript解决您的问题:https://stackoverflow.com/a/20226218/1596547

答案 1 :(得分:4)

一种解决方案是使用:focus-within选择器。

所以,你会做类似下面的事情。假设你总是在control-group内输入一些描述,只要输入被聚焦,它就会设置标签的样式。

control-group {
    &:focus-within {
        control-label {
            color: red; 
        }
    }
}

可在此处找到更多信息:https://developer.mozilla.org/en-US/docs/Web/CSS/:focus-within

答案 2 :(得分:3)

一种解决方案是将label移到DOM中的input下方但绝对定位(向父级),以便label看起来高于input } field:

<div>
  <input type="text"/>
  <label>Text</label>
</div>

在CSS中,将label移到顶部,将input移到底部:

label {
  position: absolute
  top: 0
}

input {
  position: absolute
  bottom: 0
}

并使用:focus状态更改label的样式:

input:focus + label {
    color: red
}

参见示例:

http://codepen.io/robcampo/pen/zGKLgg

在焦点上,label变为红色。不需要JS。

答案 3 :(得分:2)

使用Flexbox

CSS受事物在DOM中出现的顺序的影响,在这种情况下,null必须排在import random, os import time print("^^^^^^^^^^THIS IS HANGMAN^^^^^^^^^^") print("1. Play Game ") print("2. Quit Game ") choice = input("Please enter option 1 or 2") if choice == "1": words = ["handkerchief", "accommodate", "indict", "impetuous"] word = random.choice(words) guess = ['_'] * len(word) guesses = 7 while '_' in guess and guesses > 0: print(' '.join(guess)) character = input('Enter character: ') if len(character) > 1: print('Only enter one character.') continue if character not in word: guesses -= 1 for i, c in enumerate(word): if c == character: guess[i] = character if guesses == 0: print('You LOST!') break else: print('You have only', guesses, 'chances left to win.') else: print(''.join(guess)) print('You WON, well done') time.sleep(2) import os os.system('clear') 之后,所以;

label放在DOM中的input之前,然后使用flexbox反转它们在页面上的显示顺序。

input
label

答案 4 :(得分:0)

简单的方法是在check developer mozilla内使用:focus-within

.control-group:focus-within .control-label {
   color: red;
}

.control-group:focus-within label {
   color: red;
}

答案 5 :(得分:0)

control-group {
    &:focus-within {
        control-label {
            color: red; 
        }
    }

}

对这个人充满了爱心。没有任何效果,这也适用于 ion-label 。接受的答案。堆栈溢出不允许评论(低于 50 声望)。所以单独写<3

相关问题