我有一个父元素<ul class="dropdown-menu big">
,它包含像<li><input class="contact-form"></li>
这样的子元素。如果其中一个输入是焦点,我想在父元素上应用一些css样式,例如更改背景颜色:
jQuery(document).ready(function(){
$(".contact-form").focus(function(){
$(".dropdown-menu.big").css('background-color', '#ff5544');
});
});
但这段代码什么也不做,焦点事件上什么也不发生,Chrome调试器中也没有显示任何错误。
编辑:选择器中的空格已删除,但没有任何更改。
编辑:问题是,焦点事件从未被触发。我将代码更改为alert("Hello! I am an alert box!!");
,没有显示任何警报。为什么?
这里有一个正在工作的fiddle,背景应用于父li+blur函数,将其移除:https://jsfiddle.net/RexTangle4/o9Lsb91n/
jquery:
$('.contact-form').focus(function () {
$(this).parent().css({
backgroundColor: '#ff5544'
});
}).blur(function(){
$(this).parent().css({
backgroundColor: ''
});
});
要么删除空格:
$(".dropdown-menu.big").css('background', '#ff5544');
或者通过DOM遍历使其通过焦点元素:
$(this).closest(".dropdown-menu.big").css('background', '#ff5544');
还有一个建议是使用background
而不是background-color
签出下面的代码段:↓
$(':text').focus(function() {
$(".dropdown.big").addClass('newclass');
});
ul {
background: greenyellow;
}
.dropdown{ background:red !important;}
.newclass{background:purple !important;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class='dropdown big'>
<li>
<input type='text' />
</li>
</ul>
尝试使用样式而不是像这样的css
$(".dropdown-menu.big").focus(function () {
this.style.backgroundColor("red");
});
并确保您放置和使用像这样的真正的jquery文件
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
问题非常愚蠢,我在输入类中拼写错误——"contact from"而不是"contact form"。