我希望能够在单击时更改表单背景颜色的颜色,但是如果我甚至在表单输入框内单击它也会更改表单背景。
$('form').on('focus', 'input', function(e) {
$(this).addClass('change');
})
答案 0 :(得分:0)
$(document).on('click', 'input', function(e) {
e.stopPropagation(); // this will prevent the bubble up to the click of form
}).on('click', 'form', function(e) {
$(e.currentTarget).toggleClass('change');
})
form {
height: 150px;
width: 300px;
background-color: #ccc;
text-align: center;
padding: 20px;
}
.change {
background-color: lightgreen;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<label for="input">
Input
<input type="text" value="" name="input" />
</label>
</form>
答案 1 :(得分:0)
您可以class
输入,然后检查用户是否没有点击,请查看:
$("form").click(function(e) {
if(e.target.className != 'inputtext') {
$(this).toggleClass('change');
}
})
&#13;
form {
background: yellow;
}
.change {
background: red;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form">
First name:<br>
<input type="text" name="firstname" class="inputtext"><br>
Last name:<br>
<input type="text" name="lastname" class="inputtext">
</form>
&#13;