我有一个表格,它被分成由 div 分隔的部分,例如:
<form>
<div>
Account Details
</div>
<div>
Personal Details
</div>
<div>
...etctec
</div>
</form>
我希望当有人突出显示或关注 div 中的任何元素时,相关的 div 会使用 css 突出显示。考虑一下我已将许多处理程序应用于此表单上的某些输入元素这一事实。
最佳答案
你可以试试:
$('input').focus(
function(){
// adds the 'highlight' class to the parent
$(this).closest('div').addClass('highlight');
});
与:
$('input').blur(
function(){
// removes the 'highlight' class from the parent so only one highlight is ever visible.
$(this).closest('div').removeClass('highlight');
});
并在 CSS 中定义 highlight
类:
.highlight {
background-color: #ffa;
}
JS Fiddle demo ,请注意,在演示中,我使用 fieldset
而不是 div
来包装各种 label
和 input
元素,除此之外的原理完全相同。
更新了演示以增加美观:Revised JS Fiddle .
编辑以回应 OP 的问题:
Thats great - however theres a little problem with this code i.e that if ever an input within a div loses focus the div is shown as unhighlighted. Is there a way so that a div remains focus until an input element in another div is focused upon which the parent of the focused div would then get highlighted
是的,假设我没听错,那很简单:
$('input').focus(
function() {
$(this)
.closest('form')
.find('.highlight')
.removeClass('highlight');
$(this).closest('fieldset').addClass('highlight');
});
关于javascript - JQuery 如何使表单的一部分在聚焦时突出显示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5611339/